Home > Enterprise >  How to get connection string from appsettings.json in a .net 6 worker service?
How to get connection string from appsettings.json in a .net 6 worker service?

Time:10-10

I use the code below.

using Microsoft.Extensions.Configuration;
using WorkerService;
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
   
    services.Configure<WorkerService.DAL._DBConnStr>(Configuration.GetSection("ConnectionStrings"));

    services.AddHttpClient();
    services.AddHostedService<Worker>();
   
})
.Build();

await host.RunAsync();

The connection string in appsettings.json like this.

    {
 "Logging": {
 "LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
  }
  },
"AllowedHosts": "*",
"ConnectionStrings": {
"sqlserver1ConnectionString": "...",
"oracle1ConnectionString": "...",
..............

  }
}

There is an error in services.Configure<WorkerService.DAL._DBConnStr>(Configuration.GetSection("ConnectionStrings"));

"Configuration" doesn't exit.

How to reslove it?

CodePudding user response:

Use IHostBuilder.ConfigureServices overload accepting action with two parameters - HostBuilderContext and IServiceCollection, and use HostBuilderContext to access the configuration:

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((ctx, services) =>
    {  
        services.Configure<WorkerService.DAL._DBConnStr>(ctx.Configuration.GetSection("ConnectionStrings"));
        // ...
    })
  • Related