How To Use Third Party (Ioc) Containers In ASP.NET Core MVC

Dependency Injection is a simple implementation of Inversion of control (IoC). Inversion of Control (Ioc) is stating that objects do not create other objects to accomplish their work. In order to create objects, they need to depend on third-party containers like Unity, Autofac and Ninject.

Dependency Injection(DI)

Dependency Injection is a simple implementation of utilizing Inversion of control (IoC).

Inversion of Control (Ioc) states that objects do not create other objects to accomplish their work. In order to create objects, they need to depend on third-party containers like Unity, Autofac and Ninject.

Advantages of Using DI

  • Improves code Maintainability
  • Code reusability
  • Loosely coupled
  • Reduce class coupling
  • Improves application Testing

Why do we go for third party Ioc Container

The inbuilt DI container is very light and does not support every feature. 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 container with minimal steps.

The table will describe the advantages of Autofac Ioc container over inbuilt DI container

ASP.NETcoreBuilt-in Ioc ContainerAutofacIoc ContainerDescription
ServiceLifetime.Transientservices.
AddTransient<,>
InstancePer
Dependency()
A unique instance will be returned from each object request.
ServiceLifetime.Scopedservices.AddScope<,>In ASP.NET Core applications a scope is created around each server request. But it could be used as plain Scoped (non related to Http requests) if using DI out of ASP.NET CoreInstancePerLifetime
Scope()
This is useful for objects specific to a single unit of work that may need to nest additional logical units of work. Each nested lifetime scope will get a new instance of the registered dependency. For example, this type of lifetime scope is useful for Entity Framework DbContext objects (Unit of Work pattern) to be shared across the object scope so you can run transactions across multiple objects.
ServiceLifetime.Scopedservices.AddScope<,>In ASP.NET Core applications a scope is created around each server request, so it will work similar to InstancePerRequest, in this case.InstancePerRequest()Application types like ASP.NET Core naturally lend themselves to “request” type semantics. You have the ability to have a sort of “singleton per request.”
ServiceLifetime.
Singletonservices.AddSingleton<,>
SingleInstance()One instance is returned from all requests in the root and all nested scopes
NOInstancePer
MatchingLifetime
Scope()
you have the ability to “tag” or “name” the scope. A component with per-matching-lifetime scope will have at most a single instance per nested lifetime scope that matches a given name. This allows you to create a sort of “scoped singleton”
NOInstancePerOwned()The Owned<T> implicit relationship type creates new nested lifetime scopes. It is possible to scope dependencies to the owned instance using the instance-per-owned registrations.
NOThread Scope(based on lifetime scopes)Autofac can enforce that objects bound to one thread will not satisfy the dependencies of a component bound to another thread. While there is not a convenience method for this, you can do it using lifetime scopes.
 
Generally, Dot NET supports various DI containers, among them below list are.

Generally, Dot NET supports various DI containers, among them below list are popular containers.

  • Unity
  • Ninject
  • Autofac

In this article, I am going to talk about Autofac and How to integrate with ASP.NET CORE 2.0 with MVC.

To accomplish this task, make sure you have following things ready.

  • Visual Studio 2017 Professional

Step 1 - Creating an ASP.NET Core MVC project.

Open VS 2017 go to File->New->Project where you have to select ASP.NET core web application template and give any name you want, here I’ve given ASPNETCOREMVC-AUTOFAC.

How To Use Third Party (Ioc) Container In ASP.NET Core MVC

And click ok it will display the Web application template where you have to select web application(MVC) then click ok.

 How To Use Third Party (Ioc) Container In ASP.NET Core MVC
 
Now solution ready like below,
 
 How To Use Third Party (Ioc) Container In ASP.NET Core MVC

Step 2 - Creating a Separate Project called Employee.Model

Just right click on your solution and choose to add New Project option you’ll get below the screen where you have to select classLibrary(.NETCore) & given name EMPLOYEE.MODEL and click ok.

 How To Use Third Party (Ioc) Container In ASP.NET Core MVC

After you create you will get to see this project added under solution. Now try to add EmployeeModel class file under this project. Once you create a class file in solution will see like below,

How To Use Third Party (Ioc) Container In ASP.NET Core MVC

Inside EmployeeModel.cs file paste below properties,

  1. using System;  
  2. namespace EMPLOYEE.MODEL {  
  3.     publicclass EmployeeModel {  
  4.         publicint EmpId {  
  5.             get;  
  6.             set;  
  7.         }  
  8.         public string Name {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         publicint Salary {  
  13.             get;  
  14.             set;  
  15.         }  
  16.         public string Address {  
  17.             get;  
  18.             set;  
  19.         }  
  20.     }  

Step 3 - Create Service Employee.Service

So far we have created a web controller and model, now we have to create another project called Employee.Service. which is responsible to interact with the database. Do the same steps what we did in step 2 for creating a new project. But here we have to add two files.

  • IEmployee.cs interface file
  • Employee.cs file

These files are responsible to achieve actual crud operation.

IEmployee.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using EMPLOYEE.MODEL;  
  5. namespace EMPLOYEE.SERVICE {  
  6.     publicinterface IEmployee {  
  7.         EmployeeModel GetEmployee();  
  8.         int PostEmployee(EmployeeModel employee);  
  9.         int UpdateEmployee(EmployeeModel employee);  
  10.         int DeleteEmployee(int Id);  
  11.     }  
  12. }  

Employee.cs

  1. using EMPLOYEE.MODEL;  
  2. using System;  
  3. namespace EMPLOYEE.SERVICE {  
  4.     publicclass Employee: IEmployee {  
  5.         public EmployeeModel GetEmployee() {  
  6.             returnnew EmployeeModel();  
  7.         }  
  8.         publicint PostEmployee(EmployeeModel employeeModel) {  
  9.             //Db stuff goes here  
  10.             return  
  11.         }  
  12.         publicint UpdateEmployee(EmployeeModel employeeModel) {  
  13.             //Db stuff goes here  
  14.             return 1;  
  15.         }  
  16.         publicint DeleteEmployee(int Id) {  
  17.             //Db stuff goes here  
  18.             return 1;  
  19.         }  
  20.     }  
  21. }  

So once you set up three projects under solution it would look like below,

 How To Use Third Party (Ioc) Container In ASP.NET Core MVC

Step 4 - Add Autofac NuGet library to a web project

Go to your web project to add Autofac NuGet packages here our web project name is

ASPNETCOREMVC-AUTOFAC

Right click on this project and choose ManageNugetPackages option it will show below a screen

Here you have to search below two packages

  • Autofac
  • Extension.DependencyInjection
 How To Use Third Party (Ioc) Container In ASP.NET Core MVC

Once you add these two packages it will add under the NuGet folder of your project like below

 How To Use Third Party (Ioc) Container In ASP.NET Core MVC

Now you have to tweak in starup.cs file. Go to Starup.cs file paste below snippet under ConfigureService Method

  1. public IServiceProvider ConfigureServices(IServiceCollection services) {  
  2.     services.AddMvc();  
  3.     // Create the container builder to register services with Autofac container.  
  4.     var builder = new ContainerBuilder();  
  5.     builder.Populate(services);  
  6.     builder.RegisterType < Employee > ().As < IEmployee > ().InstancePerDependency();  
  7.     this.ApplicationContainer = builder.Build();  
  8.     // Create the IServiceProvider based on the container.  
  9.     returnnew AutofacServiceProvider(this.ApplicationContainer);  
  10. }  

The above ConfigureServices() 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.Asp.net core will use Autofac to resolve dependencies.

Now go to EmployeeController under web project and inject IEmployee interface as shown below

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using EMPLOYEE.MODEL;  
  6. using EMPLOYEE.SERVICE;  
  7. using Microsoft.AspNetCore.Mvc;  
  8. namespace ASPNETCOREMVC_AUTOFAC.Controllers {  
  9.     publicclass EmployeeController: Controller {  
  10.         private IEmployee _employee;  
  11.         public EmployeeController(IEmployee employee) {  
  12.             _employee = employee;  
  13.         }  
  14.         public EmployeeModel GetEmployee() {  
  15.             return _employee.GetEmployee();  
  16.         }  
  17.         public EmployeeModel PostEmployee(EmployeeModel employeeModel) {  
  18.             return _employee.GetEmployee();  
  19.         }  
  20.         public EmployeeModel UpdateEmployee(EmployeeModel employeeModel) {  
  21.             return _employee.GetEmployee();  
  22.         }  
  23.         publicint DeleteEmployee(int Id) {  
  24.             return Id;  
  25.         }  
  26.     }  
  27. }  

In the constructor, we injected the IEmployee interface.so Employee controller depends on IEmployee interface it would resolve by Autofac container with help of configuration we did in Starup.cs file.

This is a simple demonstration to understand quickly how to use Autofac in ASP.NET CORE MVC. Hope you liked it!