简体   繁体   中英

How to access database connection string from appsettings.json file in Program.cs file

In my Program.cs file, I currently have the following:

class Program
{
    static async Task Main(string[] args)
    {
        var serviceHost = new HostBuilder();
        serviceHost.ConfigureAppConfiguration(cb =>
        {
            cb.AddJsonFile("appsettings.json", false);
        });

        serviceHost.ConfigureServices(sc =>
        {
            // add all my services ...

            sc.AddDbContext<DiagnosticDbContext>(db =>
                db.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=ResultsDatabase;Integrated Security=True",
                    options => options.EnableRetryOnFailure(5)));
        });

       await serviceHost.RunConsoleAsync();
    }
}

In my appsettings.json file I have the connection string: 

"ConnectionStrings": { "DbContext": "Server=(localdb)\mssqllocaldb;Database=ResultsDatabase;Integrated Security=True" },


Is there a way for me to not have to write the entire connection string in my Program.cs file, and instead just refer to "ResultsDatabase" from my appsettings.json file? I have looked at other Stack Overflow articles but most of them talk about the Startup.cs file but I'm looking for it outside of this. If anyone could point me in the right direction that would be great. I am using .Net core

You can get the connection string by using Configuration property of HostBuilderContext class. So you need to use the overload of ConfigureServices that helps you inject an instance of HostBuilderContext like below:

serviceHost.ConfigureServices((hc, sc) =>
{
    sc.AddDbContext<DiagnosticDbContext>(db => 
        db.UseSqlServer(hc.Configuration.GetConnectionString("DbContext"), 
        options => options.EnableRetryOnFailure(5))
    );
});

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