Getting a connection string in a .NET Core application

I am trying to get a dynamic string dynamically from the appsettings.json file . I see that I can do this using the Launch Class Configuration property . I marked the “Configuration” field as a static field and am accessing it through the application.

I am wondering if there is a better way to get the connection string value from a .NET Core application .

+4
source share
3 answers

You can check my blog post on ASP.NET kernel configuration here .

In it, I also go through Dependency Injection from the configuration options.

Quote:

There are several ways to get the settings. One way is to use the Configuration Object in Startup.cs.

You can make the configuration available in your application globally through Dependency Injection by doing this in ConfigureServices in Startup.cs:

services.AddSingleton (Configuration);

+5
source

You can make thread safe Singletonyour variable IConfigurationdeclared in the file Startup.cs.

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
}
0
source
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");
0

Source: https://habr.com/ru/post/1658676/


All Articles