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 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 Container

AutofacIoc Container

Description

ServiceLifetime.Transientservices.AddTransient<,>

InstancePerDependency()

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 Core

InstancePerLifetimeScope()

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

NO

InstancePerMatchingLifetimeScope()

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”

NO

InstancePerOwned()

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.

NO

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

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

Now solution ready like below,

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.

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,

Inside EmployeeModel.cs file paste below properties,

using System;

namespace EMPLOYEE.MODEL {

publicclass EmployeeModel {

publicint EmpId {

get;

set;

}

public string Name {

get;

set;

}

publicint Salary {

get;

set;

}

public string Address {

get;

set;

}

}

}

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

using System;

using System.Collections.Generic;

using System.Text;

using EMPLOYEE.MODEL;

namespace EMPLOYEE.SERVICE {

publicinterface IEmployee {

EmployeeModel GetEmployee();

int PostEmployee(EmployeeModel employee);

int UpdateEmployee(EmployeeModel employee);

int DeleteEmployee(int Id);

}

}

Employee.cs

using EMPLOYEE.MODEL;

using System;

namespace EMPLOYEE.SERVICE {

publicclass Employee: IEmployee {

public EmployeeModel GetEmployee() {

returnnew EmployeeModel();

}

publicint PostEmployee(EmployeeModel employeeModel) {

//Db stuff goes here

return

}

publicint UpdateEmployee(EmployeeModel employeeModel) {

//Db stuff goes here

return 1;

}

publicint DeleteEmployee(int Id) {

//Db stuff goes here

return 1;

}

}

}

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

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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using EMPLOYEE.MODEL;

using EMPLOYEE.SERVICE;

using Microsoft.AspNetCore.Mvc;

namespace ASPNETCOREMVC_AUTOFAC.Controllers {

publicclass EmployeeController: Controller {

private IEmployee _employee;

public EmployeeController(IEmployee employee) {

_employee = employee;

}

public EmployeeModel GetEmployee() {

return _employee.GetEmployee();

}

public EmployeeModel PostEmployee(EmployeeModel employeeModel) {

return _employee.GetEmployee();

}

public EmployeeModel UpdateEmployee(EmployeeModel employeeModel) {

return _employee.GetEmployee();

}

publicint DeleteEmployee(int Id) {

return Id;

}

}

}

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!