asp.net-coreautofac

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
}

Solution

  • 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 myOptions = config.GetSection("MyOptions").Get<MyOptions>();
    

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