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"));
// ...
})