Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Configure<T> using autofac modules

What is the equivalent to the method Configure<TOptions> of the OptionsConfigurationServiceCollectionExtensions when using Autofac modules?

My ConfigureServices method looks like this, but I want to move the services.Configure<MyOptions>(Configuration.GetSection("MyOptions")) to MyModule.

public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));

    var containerBuilder = new ContainerBuilder();
    containerBuilder.Populate(services);
    containerBuilder.RegisterModule<MyModule>();

    var container = containerBuilder.Build();
    return new AutofacServiceProvider(container);
}

How does the registration look like in the Load-method of the Module

protected override void Load(ContainerBuilder builder)
{
    // configure options here
}
like image 783
Jehof Avatar asked Jun 19 '18 08:06

Jehof


2 Answers

I'm not familiar with Autofac personally, but generally speaking, all Configure<T> does is 1) bind a particular configuration section to a class and 2) register that class with the service collection, so it can be injected directly.

As a result, you can instead use the following to bind your strongly-typed configuration:

var config = config.GetSection("MyOptions").Get<MyOptions>();

And, then you'd simply register that with Autofac as a constant in singleton-scope.

like image 94
Chris Pratt Avatar answered Sep 27 '22 22:09

Chris Pratt


I recently encountered this same issue, I implemented the following so that you can still use IOptions, IOptionsMonitor and IOptionsSnapshot, but register the configuration from the AutoFac Module.

The prerequisite is that you call services.AddOptions() in ConfigureServices method:

var sfConfig = _configuration.GetSection("MyOptions");

builder.Register(ctx => new ConfigurationChangeTokenSource<MyOptions>(Options.DefaultName, sfConfig))
       .As<IOptionsChangeTokenSource<MyOptions>>()
       .SingleInstance();

builder.Register(ctx => new NamedConfigureFromConfigurationOptions<MyOptions>(Options.DefaultName, sfConfig, _ => { }))
       .As<IConfigureOptions<MyOptions>>()
       .SingleInstance();

This requires that you run services.AddOptions() within the ConfigureServices method.

In the example above, "MyOptions" is the section name in your configuration, and MyOptions type is the POCO class that has the fields to hold the result.

This is basically a conversion of what microsoft has here: https://github.com/aspnet/Options/blob/master/src/Microsoft.Extensions.Options.ConfigurationExtensions/OptionsConfigurationServiceCollectionExtensions.cs

like image 31
Jamieson Rhyne Avatar answered Sep 27 '22 20:09

Jamieson Rhyne