Thursday, October 10, 2019

ASP.NET Core 3.0 - ConfigureContainer magic

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:

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

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()