GlennSills
GlennSills

Reputation: 4187

Configuration of options from IConfigurationRoot not working?

The following code is snipped from the examples at docs.asp.net.

public void ConfigureServices(IServiceCollection services)
{
    // Setup options with DI
    services.AddOptions();

    // Configure MyOptions using config
    services.Configure<MyOptions>(Configuration);

    // Configure MyOptions using code
    services.Configure<MyOptions>(myOptions =>
    {
        myOptions.Option1 = "value1_from_action";
    });

The call to services.Configure<MyOptions>(Configuration); causes a compilation error:

cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationRoot' to 'System.Action'

Manually setting up the options works fine. Am I missing something really obvious here?

Upvotes: 17

Views: 7345

Answers (2)

Sarel Esterhuizen
Sarel Esterhuizen

Reputation: 1688

You need to add the following nuget package to your ASP Core Project if you want to configure the strongly typed config in that way.

Microsoft.Extensions.Options.ConfigurationExtensions

The extension methods contained in the package will allow you to configure the strongly typed configuration the way you want to and the way most tutorials show.

services.Configure<MyOptions>(Configuration);

Alternatively, you could add another binder package:

Microsoft.Extensions.Configuration.Binder

Configuration would then look something like this:

services.AddOptions();
services.Configure<MyOptions>(x => Configuration.Bind(x));

This is the downside of having so many modular packaged up extensions. It gets easy to lose track of where functionality exists.

Upvotes: 12

tessierp
tessierp

Reputation: 526

I had the same problem and I found out you need to add this extension to your project :

Microsoft.Extensions.Options.ConfigurationExtensions

Upvotes: 39

Related Questions