My previous articles, Using In-built Dependency Injection Framework in Asp.Net Core MVC and View Injection, Action Injection and Resolving Framework Services using Asp.Net Core MVC DI Container gave an overview and how to use the inbuilt DI containers to build loosely coupled application with Asp.Net Core. If you are new to Asp.Net Core, I suggest you to read the below articles for getting started in Asp.Net Core framework.
Start Learning Asp.Net Core - Part 1 - Introduction and Understanding the Basics & Fundamentals
Start Learning Asp.Net Core - Part 3 - Creating Deployment Package
Start Learning Asp.Net Core - Part 4 - Deploying and Hosting Asp.Net Core Application
To read how to use StructureMap instead of the inbuilt container, refer the below article.
Replacing the Inbuilt DI Container with StructureMap in Asp.Net Core MVC
The inbuilt DI container is very light and does not support every feature a full-fledged IOC containers support. As I said in the previous article, the default container that comes with the inbuilt framework is not full-fledged and it needs to be replaced with a third party container for a full DI support. Asp.Net Core is designed to replace the inbuilt container with a third party implementation very easily. In this article, let’s see how to use Autofac IOC container for resolving framework and application dependencies.
I will use Visual Studio 2017 Community Edition for demonstration in this article. Visual Studio Community Edition is free for developers, you can download it from here. Assuming you have Visual Studio 2017, we will go ahead and create a simple Asp.Net Core MVC site.
Creating Asp.Net Core Project in Visual Studio 2017
-
Open Visual Studio 2017. Click New > New Project.
-
Select .Net Core templates and “Asp.Net Core Web Application (.NET Core)” project type and click OK.
-
Select Asp.Net Core project template. I have selected “Web Application” and left the Authentication to No Authentication. Click Ok.
This will create the Asp.Net Core project with all the configuration to start developing Asp.Net Core MVC project.
Including Autofac Nuget package
Next, let’s include the Autoface Nuget package and configure it in our Asp.Net Core project. To do this, right click the project and click “Manage Nuget Packages..”. In Browse tab, enter “Autofac.Extensions.DependencyInjection” as seen below.
Install the package by clicking Install button. Accept any licensing agreements it may ask you during installation.
Now, let’s go ahead and modify the Startup class to replace the inbuilt container with Autofac IOC container.
Modifying Startup Class to Use Autofac
Open Startup.cs class and you see the ConfigureServices() method as seen below.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddDbContext<DBModel>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IPostRepository, PostRepository>();
services.AddTransient<SiteAnalyticsServices>();
}
In the above code, I have added the application dependencies for DBModel, IPostRepository and SiteAnalyticsServices services into the inbuilt container. To use Autofac, we need to first change the ConfigureServices() method signature to return IServiceProvider instead of void and then add the dependencies to AutoFac container. Refer the code below.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddDbContext<DBModel>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//Now register our services with Autofac container
var builder = new ContainerBuilder();
builder.RegisterType<PostRepository>().As<IPostRepository>();
builder.RegisterType<SiteAnalyticsServices>();
builder.Populate(services);
var container = builder.Build();
//Create the IServiceProvider based on the container.
return new AutofacServiceProvider(container);
}
Include Autofac and Autofac.Extensions.DependencyInjection namespace for the above code to work.
The above modified ConfigureServices() now returns IServiceProvider and uses Autofac container for resolving dependencies. The builder.Populate(services) will copy all the existing dependencies added into the IServiceCollection into Autofac container. That’s it. Executing the app, the Asp.Net core will use Autofac to resolve dependencies.
An alternate approach to map the dependencies to an external class file, the Autofac allows to define the dependencies in Module class to keep the ConfigureServices() method clean and simple. To do this, include a class file and name it as RepositoryRegistry and derive it from the Registry class found in Autofac namespace. Code below.
public class RepositoryHandlerModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<PostRepository>().As<IPostRepository>();
}
}
We can now change the ConfigureServices() method in Startup class to use the above Module class as seen below.
//Now register our services with Autofac container
var builder = new ContainerBuilder();
builder.RegisterModule(new RepositoryHandlerModule());
builder.Populate(services);
var container = builder.Build();
// Create the IServiceProvider based on the container.
return new AutofacServiceProvider(container);
Thus, we have understood how to replace the inbuilt DI container with Autofac IOC container in Asp.Net Core applications in this article. Hope you liked it!
Happy Coding!!
Further Reading
Read Difference Between Asp.Net and Asp.Net Core for a side by side difference.