The configuration is already pre-registered by the host that is used with ASP.NET Core. So you can just register your service as you would any other singleton service, and have it depend on the configuration by requiring IConfiguration in the constructor:
public class MyService
{
private readonly IConfiguration _config;
public MyService(IConfiguration config)
{
_config = config;
}
}
You can then register this service as a singleton directly in your ConfigureService method:
services.AddSingleton<MyService>();
Things that now depend on your service, for example constructors, will automatically get a reference to that service instance. And since it is registered as singleton, it will only be created once by the DI container.
If you want a bit more control over your configuration, then I would suggest you to adapt the options pattern to make sure that you can work with strongly typed configuration and to avoid unrelated configuration value from spilling into services that shouldn’t not have access to them.
Комментариев нет:
Отправить комментарий