How to integrate Dependency Injection in ASP.Net MVC using Unity Container

Today, we will learn about injecting Dependency Injection in ASP.Net MVC using Unity Container.
Before going further, we will learn what is Dependency Injection and what is Unity Container.

Dependency Injection is a Software design pattern which we use in C# to reduce class dependency, in other words we can say that it used to increase the loose coupling and makes the code more object oriented.

The Unity Container (Unity) is a lightweight, extensible dependency injection container. As we know, there are many dependency injection containers and unity is one of them.

Steps to implement DI (Dependency Injection) in project are as follows:-

Step 1 – Create a new ASP.Net MVC project

Open the Visual Studio and create a new ASP.Net MVC 4 Empty project as follows-

Dependency Injection in ASP.Net MVC

 

Step 2 – Add a new Model class

Add a new model class User.cs in Model folder of the project.

Replace the User.cs model class code with below code-

 

Step 3 – Add new interface

Add a new folder IRepository in project and add IUserRepository.cs interface in the folder.

Replace the IUserRepository.cs interface code with below code-

Add the namespace of User.cs model class in the above interface file.

 

Step 4 – Add repository class

Add a new folder Repository in project and add UserRepository.cs class in the folder.

Replace the UserRepository.cs class code with below code-

Add the required namespaces for IUserRepository.cs and User.cs model class in the above class file.

 

Step 5 – Install Unity Container package from Nuget

Run below command to install Unity Container through Nuget Package Manager console.

It will install all the required packages for Unity and will create a Bootstrapper.cs file in the root directory of project.

Now replace the Bootstrapper.cs class file code with below code –

Here you can see that I have registered IUserRepository.cs interface and UserRepository.cs class file.

 

Step 6 – Create a new Controller

Create a new HomeController.cs controller in the project as below –

Dependency Injection in ASP.Net MVC

Replace the HomeController.cs class code with below code-

Import the required namespaces.

 

Step 7 – Create a View

Create a new view Index as below – Make the view Strongly Typed with User.cs model class and choose Scaffolding templates: List

Dependency Injection in ASP.Net MVC

 

Step 8 – Run the project

You will see the list details as follows –

2017-01-05_1312

 

Conclusion

If you put a break point at HomeController constructor, you will see that the Unity has injected the implementation class

Dependency Injection in ASP.Net MVC

 

Follow this tutorial to Integrate Dependency Injection in ASP.Net Web Forms.

That’s all.

Thanks for reading 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *