在 .NET Core 应用程序中获取连接字符串
Get connection string in .NET Core application
我正在尝试从 appsettings.json 文件中动态获取 连接字符串 。我看到我可以通过 Configuration 属性 of startup class 来做到这一点。我已将配置字段标记为静态字段并在整个应用程序中访问它。
我想知道是否有 更好的 方法从 .NET Core 应用程序获取连接字符串值。
您可以对 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
}
您可以查看我关于 ASP.NET 核心配置 here 的博客文章。
在其中我还通过了配置选项的依赖注入。
引用:
There are a couple ways to get settings. One way would be to use the
Configuration object in Startup.cs.
You can make the configuration available in your app globally through
Dependency Injection by doing this in ConfigureServices in Startup.cs:
services.AddSingleton(Configuration);
private readonly IHostingEnvironment _hostEnvironment;
public IConfiguration Configuration;
public IActionResult Index()
{
return View();
}
public ViewerController(IHostingEnvironment hostEnvironment, IConfiguration config)
{
_hostEnvironment = hostEnvironment;
Configuration = config;
}
并在 class 中您需要连接字符串
var connectionString = Configuration.GetConnectionString("SQLCashConnection");
我正在尝试从 appsettings.json 文件中动态获取 连接字符串 。我看到我可以通过 Configuration 属性 of startup class 来做到这一点。我已将配置字段标记为静态字段并在整个应用程序中访问它。
我想知道是否有 更好的 方法从 .NET Core 应用程序获取连接字符串值。
您可以对 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
}
您可以查看我关于 ASP.NET 核心配置 here 的博客文章。
在其中我还通过了配置选项的依赖注入。
引用:
There are a couple ways to get settings. One way would be to use the Configuration object in Startup.cs.
You can make the configuration available in your app globally through Dependency Injection by doing this in ConfigureServices in Startup.cs:
services.AddSingleton(Configuration);
private readonly IHostingEnvironment _hostEnvironment;
public IConfiguration Configuration;
public IActionResult Index()
{
return View();
}
public ViewerController(IHostingEnvironment hostEnvironment, IConfiguration config)
{
_hostEnvironment = hostEnvironment;
Configuration = config;
}
并在 class 中您需要连接字符串
var connectionString = Configuration.GetConnectionString("SQLCashConnection");