admin管理员组文章数量:1406911
I am working on ASP.NET Core WebAPI projects with clean architecture, and I came around the situation where I need retrieve value from appsettings.json
I am able to do so by injecting the IConfiguration to the service, like shown below. But it seems like this might not be the best way to do so.
private readonly IConfiguration _config;
public UserService(IConfiguration config)
{
_config = config;
}
Is there any better way to inject the values into the services.
I am working on ASP.NET Core WebAPI projects with clean architecture, and I came around the situation where I need retrieve value from appsettings.json
I am able to do so by injecting the IConfiguration to the service, like shown below. But it seems like this might not be the best way to do so.
private readonly IConfiguration _config;
public UserService(IConfiguration config)
{
_config = config;
}
Is there any better way to inject the values into the services.
Share asked Mar 4 at 8:12 Anuj KarkiAnuj Karki 6196 silver badges29 bronze badges2 Answers
Reset to default 2Use the 'options' pattern as documented here and here.
I prefer to take dependencies on my own option types and then use a factory method to take care of the DI. This is not essential, you could just take a dependency on IOptions<T>
:
internal class MyCalculator {
public MyCalculator(CalculatorOptions options) { }
}
// ...
builder.Services
.AddOptions<CalculatorOptions>()
.BindConfiguration(CalculatorOptions.SectionKey)
.ValidateOnStart();
builder.Services
.AddSingleton(resolver =>
resolver.GetRequiredService<IOptions<CalculatorOptions>>().Value);
A service in a layer closer to the "core" could expose strongly typed options and inject them.
E.g. a UserService
could expose the definition of UserOptions
, and doesn't really care about how they are bound.
https://learn.microsoft/en-us/aspnet/core/fundamentals/configuration/options
class UserService(IOptions<UserOptions>) {...}
record UserOptions(Url IdentityEndpoint, ...);
//Program.cs
services.TryAddScoped<UserService>()
.AddOptions<UserOptions>()
.BindConfiguration("User")
//appsettings.json
"User": {
"IdentityEndpoint": "https://identity.yourapp/"
}
Edit: Late to the party
本文标签: aspnet core webapiWhat is the best way to inject IConfiguration value into servicesStack Overflow
版权声明:本文标题:asp.net core webapi - What is the best way to inject IConfiguration value into services - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745055706a2639921.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论