CodeDigest.Com Logo
Featured:

Using Autofac Instead of Inbuilt DI Container in Asp.Net Core MVC

Tagged as: Asp.Net Core Asp.Net Core MVC Posted By

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 2-Understand Project Structure and Startup Class in Visual Studio 2017

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

  1. Open Visual Studio 2017. Click New > New Project.

  2. Select .Net Core templates and “Asp.Net Core Web Application (.NET Core)” project type and click OK.

  1. 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.

 



Feedback

Comments

Good job
"alert("you are gay")"
Commented by name on 8/6/2020 12:00:19 AM

Satheesh Babu Sucks Homo Dick
who is the unit inch goat humper dumb sob who posted this peice of trash rofl
Commented by Satheesh Babu The Dick Sucker on 5/9/2020 4:50:46 PM

Inshort ,best explanation,great work !
Thx Thx Thx man it's really help !!
Commented by Net Core Learner on 4/14/2019 4:12:03 PM

Great work
Really saved my day
Commented by kaushik on 2/25/2019 6:51:14 AM

Cheer
Thanks for the article. My dude have fade out!!
Commented by Yunior Laureano on 9/17/2018 6:29:50 AM

Nice
Clean and simple.
Commented by MD on 7/2/2018 6:34:28 PM

why other ioc are needed inbuilt ioc not sufficient
Commented by sURESH on 6/4/2018 1:25:43 AM

Good job
good one <a href="coder-juggernaut.blogspot.com">keep it up</a>
Commented by TT on 11/14/2017 1:39:36 AM

nice post
good one <a href="https://coder-juggernaut.blogspot.in/2017/11/create-zip-file-using-c-extracting-zip.html">keep it up</a>
Commented by Tonz on 11/14/2017 1:36:49 AM