我试图获得连接字符串动态从appsettings.json文件。我看到我可以通过配置属性启动类。我已将配置字段标记为静态字段,并通过应用程序访问它。在.NET核心应用程序中获取连接字符串
我想知道是否有更好获取连接字符串值的方法从.NET Core应用程序。
我试图获得连接字符串动态从appsettings.json文件。我看到我可以通过配置属性启动类。我已将配置字段标记为静态字段,并通过应用程序访问它。在.NET核心应用程序中获取连接字符串
我想知道是否有更好获取连接字符串值的方法从.NET Core应用程序。
您可以查看我的博客文章,关于ASP.NET Core Configuration here。
其中我也通过配置选项的依赖注入。
报价:
有一对夫妇的方式来获取设置。一种方法是在Startup.cs中使用 配置对象。
您可以通过在Startup.cs在ConfigureServices这样做使你的应用程序可用的配置通过全球 依赖注入:
services.AddSingleton(配置);
您可以在Startup.cs
文件中声明的变量IConfiguration
执行线程安全Singleton
。
private static object syncRoot = new object();
private static IConfiguration configuration;
public static IConfiguration Configuration
{
get
{
lock (syncRoot)
return configuration;
}
}
public Startup()
{
configuration = new ConfigurationBuilder().Build(); // add more fields
}
private readonly IHostingEnvironment _hostEnvironment;
public IConfiguration Configuration;
public IActionResult Index()
{
return View();
}
public ViewerController(IHostingEnvironment hostEnvironment, IConfiguration config)
{
_hostEnvironment = hostEnvironment;
Configuration = config;
}
,并在课堂上要连接字符串
var connectionString = Configuration.GetConnectionString("SQLCashConnection");
您可以通过注入在ASP.NET核心的依赖注入的服务'Configuration'对象 - [实例点击这里](HTTPS:/ /radu-matei.github.io/blog/aspnet-core-configuration-greeting/#making-use-of-asp-net-core-dependency-injection) –
如何将Configuration对象注入只有无参数构造函数的类?甚至我怎样才能注入数据库上下文到只有无参数构造函数的类? –
至少在ASP.NET核心中,推荐的方法是使用考虑SoC和ISP原则的选项模式: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration#using-options -and-configuration-objects 这些原则也应该考虑用于.NET Core解决方案。 –