[英]Using appsettings.json in .Net 6 Worker service
Is I wanted to add a singleton service that is dependent on appsettings.我想添加一个依赖于 appsettings 的 singleton 服务吗?
How would I do this in the.Net 6 worker service startup?我将如何在 .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();
At the moment you're trying to register an instance of ServiceIwantToCall
.目前您正在尝试注册ServiceIwantToCall
的实例。 You can instead register a factory method to resolve one, and once it's resolved it will be a singleton. For example, this anonymous method:您可以改为注册一个工厂方法来解析一个,一旦它被解析,它将是一个 singleton。例如,这个匿名方法:
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.