.Net Core Autofac Migration

Why do you still want to use autofac?

Chewy2Theo
2 min readMay 29, 2021

--

Yes I know that .Net core now comes with a quite convenient IOC container built in. I did try to use the built in one and I have to say it’s probably the best that Microsoft has so far. However, it could be that I’ve just been using autofac for a long time now and it formed a lot of bias concepts. I like a lot of the convenient features that Autofac offers, such as modulization, assembly registration. Although these features are also built in within .Net core IOC, they’re still not as easily configured as it is in Autofac. So for those of you who are with me, let’s migrate the same autofac setup.

First let’s get all the nuget packages you need for the program.cs code

using System.IO;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
public static void Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new
AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(
webHostBuilder =>
{
webHostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
})
.Build();
host.Run();
}

You can register all the services that has a single interface through the assembly just like good old days.

var assembly = Assembly.GetExecutingAssembly();builder.RegisterAssemblyTypes(assembly)
.AsImplementedInterfaces()
.PropertiesAutowired()
.InstancePerLifetimeScope();

Remember to register your DbContext and Unit Of Work using InstancePerLifetimeScope. Remember that InstancePerRequest no longer works in .Net Core as the scope control is handled by the built in .Net Core IOD container. So InstancePerLifetimeScope will give you the same effect if you configure the startup.cs properly.

Now in your startup.cs

A few key points with the startup.cs above.

  1. Remember to register your DbContext both in autofac and in startup.cs
  2. After your configuration in program.cs, on application start up the ConfigureContainer will be called
  3. To register controllers, I was not able to use the same assembly registration that I used for services, so here I introduced a different method of registration through the name of the class. See line 64 above

Now your autofac is migrated and you’re ready to move on.

Below are the sources that I used

This article is a part of the .Net to .Net Core Migration Series
https://theochiu2010.medium.com/net-to-net-core-migration-2eb31584f95c

--

--

Chewy2Theo

Just another developer who's into lazy tools that can make my life easier, and hopefully yours too.

Recommended from Medium

Lists

See more recommendations