Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the configuration of .NET Core options not work with a generic type parameter?

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
    }
}
like image 287
Emaro Avatar asked May 20 '19 09:05

Emaro


People also ask

What is difference between configure and ConfigureServices in .NET Core?

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.

Does .NET Core support app config?

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.

What is options pattern in .NET Core?

The options pattern uses classes to provide strongly typed access to groups of related settings.

How do I use IOptions in NET Core 6?

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.


1 Answers

You need to use services.Configure as below:

services.Configure<MyOption>(setting =>
{  
    Configuration.GetSection("MyOption").Bind(setting);  
});  
like image 165
akshayblevel Avatar answered Sep 18 '22 20:09

akshayblevel