【问题标题】:How to access database connection string from appsettings.json file in Program.cs file如何从 Program.cs 文件中的 appsettings.json 文件访问数据库连接字符串
【发布时间】:2020-07-28 09:25:04
【问题描述】:

在我的 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: 

“连接字符串”:{ “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】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2020-04-17
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多