在 .Net 6 Worker 服务中使用 appsettings.json
Using appsettings.json in .Net 6 Worker service
我想添加依赖于 appsettings 的单例服务吗?
我如何在 .Net 6 worker 服务启动中执行此操作?
using AutoMapper;
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
services.AddSingleton(mapper);
services.AddSingleton<IOrderNumberGenerator, OrderNumberGenerator>();
services.AddSingleton(new ServiceIwantToCall(<--I need too use apsettings here-->));
})
.Build();
await host.RunAsync();
目前您正在尝试注册 ServiceIwantToCall
的实例。您可以改为注册一个工厂方法来解析一个,一旦它被解析,它将成为一个单例。例如这个匿名方法:
services.AddSingleton(serviceProvider => {
// resolve the configuration provider from the container
IConfiguration config = serviceProvider.GetRequiredService<IConfiguration>();
// get the config value and instantiate a ServiceIwantToCall
// return the instantiated service
string someValue = config["myValueKey"];
return new ServiceIwantToCall(someValue);
});
我想添加依赖于 appsettings 的单例服务吗?
我如何在 .Net 6 worker 服务启动中执行此操作?
using AutoMapper;
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
services.AddSingleton(mapper);
services.AddSingleton<IOrderNumberGenerator, OrderNumberGenerator>();
services.AddSingleton(new ServiceIwantToCall(<--I need too use apsettings here-->));
})
.Build();
await host.RunAsync();
目前您正在尝试注册 ServiceIwantToCall
的实例。您可以改为注册一个工厂方法来解析一个,一旦它被解析,它将成为一个单例。例如这个匿名方法:
services.AddSingleton(serviceProvider => {
// resolve the configuration provider from the container
IConfiguration config = serviceProvider.GetRequiredService<IConfiguration>();
// get the config value and instantiate a ServiceIwantToCall
// return the instantiated service
string someValue = config["myValueKey"];
return new ServiceIwantToCall(someValue);
});