如何从Program.cs文件中的appsettings.json文件访问数据库连接字符串

问题描述 投票:0回答:1

在我的Program.cs文件中,当前具有以下内容:

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”:“服务器=(localdb)\ mssqllocaldb;数据库= ResultsDatabase;集成安全性= 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
c# sql-server .net-core configuration connection-string
1个回答
1
投票

您可以通过使用Configuration类的HostBuilderContext属性来获取连接字符串。因此,您需要使用ConfigureServices的重载来帮助您注入HostBuilderContext的实例,如下所示:

serviceHost.ConfigureServices((hc, sc) =>
{
    sc.AddDbContext<DiagnosticDbContext>(db => 
        db.UseSqlServer(hc.Configuration.GetConnectionString("DbContext"), 
        options => options.EnableRetryOnFailure(5))
    );
});
© www.soinside.com 2019 - 2024. All rights reserved.