Reputation: 1373
I am building a .net minimal api with a lot of settings defined via appsettings.json.
But how to use this setting classes in program.cs without the compiler generating the warning:
ASP0000 Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.
What I do is:
var builder = WebApplication.CreateBuilder(args); // Create a WebApplication builder
builder.Services.AddEndpointsApiExplorer();
builder.Services.Configure<MYSettingFromAppsettings>(
builder.Configuration.GetSection(MYSettingFromAppsettings.Position));
builder.Services.AddSingleton(resolver =>
resolver.GetRequiredService<IOptions<MYSettingFromAppsettings>>().Value);
...//same for all the other settings
var corsConfig = builder.Services.BuildServiceProvider().GetRequiredService<MYSettingFromAppsettings>();
// use settings
To be clear, I do not only use the settings in program.cs I also us it via DI in the services (IOptions options)
So, what is best practice to work with type save setting classes in program.cs and also via DI?
Upvotes: 2
Views: 34
Reputation: 142008
The following:
var corsConfig = builder.Services.BuildServiceProvider().GetRequiredService<MYSettingFromAppsettings>();
Builds the service provider which should be avoided.
If you need to bind cofiguration before building container you can do something like:
var cfg = config.GetSection(MYSettingFromAppsettings.Position)
.Get<MYSettingFromAppsettings>();
You can use the bound value (cfg
) to register it in the DI container (though note that it will not reflect the configuration changes even if the provider supports it)
Upvotes: 2