Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way to configure Autofac in ASP.NET Core 3.0

In ASP.NET Core 2.0, I used ConfigureServices method on Startup class to wire-up Autofac, wrap existing services registrations and add additional ones.

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Standard service registrations (ex: services.AddMvc())
    // ...
    
    // Autofac
    var builder = new ContainerBuilder();
    builder.Populate(services); // wrap service registrations
    builder.RegisterModule<MyModule>(); // add extra registrations

    this.ApplicationContainer = builder.Build();
    return new AutofacServiceProvider(this.ApplicationContainer);
}

Since ConfigureService method is void in ASP.NET Core 3.0 and no longer supports return parameter IServiceProvider, how do I wire up Autofac?

like image 273
Nenad Avatar asked Sep 06 '19 12:09

Nenad


1 Answers

ASP.NET Core 3.0 IHostBuilder has extension method UseServiceProviderFactory, which can be used to register AutofacServiceProviderFactory:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder => {
                webBuilder.UseStartup<Startup>();
            })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory());
}

Registered provider will automatically wrap all standard services registered in void ConfigureServices(IServiceCollection services) method.

There is no need for lines:

public void ConfigureContainer(ContainerBuilder builder)
{
    // ...
    builder.Populate(services); // Not needed!
    // ...
    return new AutofacServiceProvider(this.ApplicationContainer); // Not needed!
}

To add additional Autofac-specific registrations, ConfigureContainer(ContainerBuilder builder) method on startup class can be used:

public partial class Startup
{
    public void ConfigureContainer(Autofac.ContainerBuilder builder)
    {
        builder.RegisterModule<MyModule>();
    }
}

Additional info can be found in this Github issue.

like image 80
Nenad Avatar answered Oct 05 '22 11:10

Nenad