Как получить доступ к строке подключения к базе данных из файла appsettings. json в файле Program.cs - PullRequest
1 голос
/ 15 апреля 2020

В моем файле 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": "Server = (localdb) \ mssqllocaldb; База данных = 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

1 Ответ

3 голосов
/ 15 апреля 2020

Вы можете получить строку подключения, используя свойство Configuration класса HostBuilderContext. Поэтому вам нужно использовать перегрузку ConfigureServices, которая поможет вам внедрить экземпляр HostBuilderContext, как показано ниже:

serviceHost.ConfigureServices((hc, sc) =>
{
    sc.AddDbContext<DiagnosticDbContext>(db => 
        db.UseSqlServer(hc.Configuration.GetConnectionString("DbContext"), 
        options => options.EnableRetryOnFailure(5))
    );
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...