ConfigureContainer in .NET Core 3.1 Generic Host implementation

8.7k views Asked by At

I am trying to migrate our framework project to .NET Core 3.1. As part of the migration, I am trying to register modules via ConfigureContainer method provided by the GenericHost. This is what I have:

Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new 
                         WorkerServiceDependencyResolver.WorkerServiceDependencyResolver()))

And my WorkerServiceDependencyResolver has the following:

builder.RegisterModule(new FirstModule());
builder.RegisterModule(new SecondModule());

But when I do it this way, my application doesn't run, it starts without any error, but doesn't do anything.

But If I write it this way (this is how we had in .NET Framework):

var builder = new ContainerBuilder();
builder.RegisterModule(new FirstModule());
builder.RegisterModule(new SecondModule());
_container = builder.Build();

Everything works as expected when I explicitly build the container, but my understanding was that we do not need that in .NET Core?

Any inputs are greatly appreciated.

Cheers!

1

There are 1 answers

2
VRoxa On

By specifying to the IHostBuilder that the Service Provider Factory is an AutofacServiceProviderFactory, it allows you create to a method right inside your Startup class, called ConfigureContainer which takes the ContainerBuilder as a parameter.

This is how you would instantiate the IHostBuilder. Nothing fancy, just following the ASP NET Core guide.

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

Then, in the Startup class, add that method.

public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;

    public IConfiguration Configuration { get; }

    // ...

    public void ConfigureContainer(ContainerBuilder builder)
    {
        // Here you register your dependencies
        builder.RegisterModule<FirstModule>();
    }

    // ...
}

Then, your IContainer will be the IOC Container of your ASPNET Core application scope.
Notice than the builder is not being built at any time. This will be done by the IHostBuilder at some point (making use of the Autofac extension).

Hope that helps.