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
AI
sg
One of the more pragmatic ways to get going on the current AI hype, and to get some value out of it, is by leveraging semantic search. This is, in itself, a relatively simple concept: You have a bunch of documents and want to find the correct one based on a given query. The semantic part now allows you to find the correct document based on the meaning of its contents, in contrast to simply finding words or parts of words in it like we usually do with lexical search. In our last projects, we gathered some experience with search bots, and with this article, I'd love to share our insights with you.
17.05.2024
Angular
sl_300x300
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_300x300
.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