ASP.NET Core – Update To Autofac 4.6.1 Recommended – More Than A Bugfix Release

In this article:

pg
Pawel Gerr is architect consultant at Thinktecture. He focuses on backends with .NET Core and knows Entity Framework inside out.

If you are using Autofac in your ASP.NET Core application then I recommend to update Autofac to version 4.6.1. This bugfix release brought a change how child scope handle additional registrations so that some errors like Cannot resolve parameter 'IOptionsFactory<KestrelServerOptions>' just disappear.

With additional registrations I mean the following:

				
					var builder = new ContainerBuilder();

using (var container = builder.Build())
{
    using (var childScope = container.BeginLifetimeScope(innerBuilder =>
        {
            // additional registration that are known by childScope only
            innerBuilder.RegisterType<Foo>().AsSelf();
        }))
    {
        ...
    }
}
				
			

When using a child scope during the setup of an ASP.NET Core application having Autofac 4.6.0 or lower then you had to use the IContainer (= root scope) itself or use a workaround to register MVC components. The first option is not recommended because a DI container should be considered as immutable. The second option could be confusing if you don’t know the internals of Autofac.

The second options looks like this:

				
					public class Startup
{
    public Startup(ILifetimeScope childScope)
    {
        _childScope = childScope;
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // All singleton are "rebased" to "aspNetScopeTag"
        const string aspNetScopeTag = "AspNetScope";

        _aspNetScope = _childScope.BeginLifetimeScope(aspNetScopeTag, 
            builder => builder.Populate(services, aspNetScopeTag));

         return new AutofacServiceProvider(_aspNetScope);
    }
    ...
}

				
			

 With Autofac 4.6.1 you just call Populate without any confusing parameters like aspNetScopeTag.

				
					public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    _aspNetScope = _childScope.BeginLifetimeScope(builder => builder.Populate(services));

    return new AutofacServiceProvider(_aspNetScope);
}

				
			

Want to try it out? I have prepared 2 projects: AspNetCore2_Autofac460 and AspNetCore2_Autofac461 in my github repo. Download the sources and start the applications with dotnet run in the corresponding folder. The first one will raise an error the latter will start the web server successfully.

P.S.: Missing context? Why someone would want to provide its own DI container instead of using IServiceCollection and be done with it? Then read my blog post ASP.NET Core in production: Take back control of your web app or the follow-up post ASP.NET Core in production: Graceful shutdown and reacting to aborted requests.

Free
Newsletter

Current articles, screencasts and interviews by our experts

Don’t miss any content on Angular, .NET Core, Blazor, Azure, and Kubernetes and sign up for our free monthly dev newsletter.

EN Newsletter Anmeldung (#7)
Related Articles
Angular
SL-rund
If you previously wanted to integrate view transitions into your Angular application, this was only possible in a very cumbersome way that needed a lot of detailed knowledge about Angular internals. Now, Angular 17 introduced a feature to integrate the View Transition API with the router. In this two-part series, we will look at how to leverage the feature for route transitions and how we could use it for single-page animations.
15.04.2024
.NET
KP-round
.NET 8 brings Native AOT to ASP.NET Core, but many frameworks and libraries rely on unbound reflection internally and thus cannot support this scenario yet. This is true for ORMs, too: EF Core and Dapper will only bring full support for Native AOT in later releases. In this post, we will implement a database access layer with Sessions using the Humble Object pattern to get a similar developer experience. We will use Npgsql as a plain ADO.NET provider targeting PostgreSQL.
15.11.2023
.NET
KP-round
Originally introduced in .NET 7, Native AOT can be used with ASP.NET Core in the upcoming .NET 8 release. In this post, we look at the benefits and drawbacks from a general perspective and perform measurements to quantify the improvements on different platforms.
02.11.2023