Where the built-in Inversion Of Control (IOC), aka Dependency Injection (DI), container of ASP.NET MVC will meet most needs, sometimes we’ll want to utilize more advanced features of alternate IOC containers. In the example below we are configuring for the use of Autofac (line 56), using a pattern consistent with existing code – an extension method.

The extension method AddAutofacProvider code follows below:

Note on line 13 above that we have an optional “builderCallback” action. This provides the Startup ConfigureService method access to the builder instance created above on line 16. Below on lines 56-60 is an example of how it might be used:

Source code follows:
public static IServiceProvider AddAutofacProvider(
this IServiceCollection services,
Action<ContainerBuilder> builderCallback = null)
{
// Instantiate the Autofac builder
var builder = new ContainerBuilder();
// If there is a callback use it for registrations
builderCallback?.Invoke(builder);
// Populate the Autofac container with services
builder.Populate(services);
// Create a new container with component registrations
var container = builder.Build();
var provider = new AutofacServiceProvider(container);
// When application stops then dispose container
container.Resolve<IApplicationLifetime>()
.ApplicationStopped.Register(() => container.Dispose());
// Return the provider
return provider;
}