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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With