I have a .NET Core WebApi project. To read the appsettings in an easy way, I configure the options to be injected with DI. This works fine. However if I try to call Configure<>()
with a generic type parameter, I get an error.
Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action'
The method overloads apart from Configure<T>(Action<T> configureOptions)
seem not to be available anymore.
Why does the call not work with generic type parameters?
Startup.cs
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// services.AddMvc() etc...
services.AddOptions();
// Works fine
services.Configure<MyOption>(Configuration.GetSection(nameof(MyOption)));
}
private void AddOption<T>(IServiceCollection services)
{
// Wont work
services.Configure<T>(Configuration.GetSection(nameof(T)));
services.Configure<T>(Configuration.GetSection(""));
}
}
MyOption.cs
public class MyOption
{
public bool MyProp { get; set; }
}
appsettings.json
{
"MyOption": {
"MyProp": true
}
}
In the Startup class, first, ConfigureServices is called, allowing us to register services that we'll want to use in our application. Then, the Configure method is called where the request pipeline is set up. After all that, our application is up and running and is ready to handle incoming requests.
Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.
The options pattern uses classes to provide strongly typed access to groups of related settings.
IOptions is singleton and hence can be used to read configuration data within any service lifetime. Being singleton, it cannot read changes to the configuration data after the app has started. Run the app and hit the controller action. You should be able to see the values being fetched from the configuration file.
You need to use services.Configure as below:
services.Configure<MyOption>(setting =>
{
Configuration.GetSection("MyOption").Bind(setting);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With