.Net Core Autofac Migration
Why do you still want to use autofac?
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 Microsoft.Extensions.Hosting;public static void Main(string args)
var host = Host.CreateDefaultBuilder(args)
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)
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.
- Remember to register your DbContext both in autofac and in startup.cs
- After your configuration in program.cs, on application start up the ConfigureContainer will be called
- 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
How to enable property injection on controllers using Autofac and ASP.NET Core?
Yeah, setting up property injection for controllers with autofac is a bit tricky ;) but here is how it works. With…
Assembly Scanning - Autofac 6.0.0 documentation
Otherwise known as convention-driven registration or scanning, Autofac can register a set of types from an assembly…
This article is a part of the .Net to .Net Core Migration Series