简体   繁体   中英

Get connection string in .NET Core application

I'm trying to get connection string dynamically from appsettings.json file. I see that I can do that via Configuration property of startup class. I've marked Configuration field as static field and access it across the app.

I'm wondering if there is a better way to get connection string value from .NET Core app.

You can check my blog article on ASP.NET Core Configuration here .

In it I also go through Dependency Injection of configuration options.

Quote:

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);

You can do a thread-safe Singleton of your IConfiguration variable declared in the Startup.cs file.

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;
    }

and in class that you want connection string

 var connectionString = Configuration.GetConnectionString("SQLCashConnection");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM