Last week I blogged about the changes I had to make to let Autofac work with ASP.NET Core 3.0. Inside my Startup.cs file I had to use the .ConfigureContainer() method:
public void ConfigureContainer(ContainerBuilder builder) | |
{ | |
builder.RegisterModule(new AutofacModule()); | |
} |
But where is this method coming from? Letās dig into the ASP.NET Core source code to find outā¦
The source of all magic is the StartupLoader class: https://github.com/aspnet/Hosting/blob/rel/1.1.0/src/Microsoft.AspNetCore.Hosting/Internal/StartupLoader.cs.
This class uses reflection to find the following 3 methods in the Startup.cs file:
- a Configure() method
- a ConfigureServices() method
- a ConfigureContainer() method
var configureMethod = FindConfigureDelegate(startupType, environmentName); | |
var servicesMethod = FindConfigureServicesDelegate(startupType, environmentName); | |
var configureContainerMethod = FindConfigureContainerDelegate(startupType, environmentName); |
If you want environment-specific setup you can put the environment name after the Configure
part, like ConfigureDevelopment
, ConfigureDevelopmentServices
, and ConfigureDevelopmentContainer
. If a method isnāt present with a name matching the environment itāll fall back to the default.
If a ConfigureContainer() method is found, the IServiceProviderFactory<TContainerBuilder> CreateBuilder method is invoked and the created builder is passed as a parameter to the ConfigureContainer()
// We have a ConfigureContainer method, get the IServiceProviderFactory<TContainerBuilder> | |
var serviceProviderFactoryType = typeof(IServiceProviderFactory<>).MakeGenericType(configureContainerMethod.GetContainerType()); | |
var serviceProviderFactory = hostingServiceProvider.GetRequiredService(serviceProviderFactoryType); | |
// var builder = serviceProviderFactory.CreateBuilder(services); | |
var builder = serviceProviderFactoryType.GetMethod(nameof(DefaultServiceProviderFactory.CreateBuilder)).Invoke(serviceProviderFactory, new object[] { services }); | |
configureContainerCallback.Invoke(builder); | |
// applicationServiceProvider = serviceProviderFactory.CreateServiceProvider(builder); | |
applicationServiceProvider = (IServiceProvider)serviceProviderFactoryType.GetMethod(nameof(DefaultServiceProviderFactory.CreateServiceProvider)).Invoke(serviceProviderFactory, new object[] { builder }); |