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 badges
Add a comment  | 

2 Answers 2

Reset to default 2

Use 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