Please enable Javascript to correctly display the contents on Dot Net Tricks!

Dependency Injection in ASP.NET MVC using Unity IoC Container

  Author : Shailendra Chauhan
Posted On : 14 Apr 2013
Total Views : 113,488   
Updated On : 23 Nov 2016
 

In previous articles, I have explained the IoC, DI pattern and DI containers. I hope, you understand well the IoC, DI pattern and and DI containers. Now you will learn how to apply it in ASP.NET MVC 4. In this article, I am going to use Unit DI Container in MVC4.

As you know, in MVC, Controller depends on Model for data processing or you can say for executing business logic. This article will explain you how can you decouple model layers from the controller layer in an ASP.NET MVC application using Unit DI Container.

Step 1 - Create a new Asp.Net MVC4 Project

First step is to create a new Asp.Net MVC4 Project using Visual Studio 2012 or 2010SP1 as shown below:

Step 2- Install Unity Container

Now install Unity.Mvc4 Container using NuGet Package Manager Console tool as shown below:

You can also do online search for Unity.Mvc4 Container by navigating to Tools=>Extension and Update..=>Online options in Visual Studio 2012 or 2010SP1 and install it.

When it will be installed successfully, you will be find the following two references add to your project and a Bootstrapper.cs class file at project level, as shown below:

using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc4;

namespace MvcNUnit
{
 public static class Bootstrapper
 {
 public static IUnityContainer Initialise()
 {
 var container = BuildUnityContainer();
 
 DependencyResolver.SetResolver(new UnityDependencyResolver(container));
 
 return container;
 }
 
 private static IUnityContainer BuildUnityContainer()
 {
 var container = new UnityContainer();
 
 // register all your components with the container here
 // it is NOT necessary to register your controllers
 
 // e.g. container.RegisterType<ITestService, TestService>(); 
 
 RegisterTypes(container);
 
 return container;
 }
 
 public static void RegisterTypes(IUnityContainer container)
 {
 
 }
 }
}

Step 3- Add a New Service Layer

Add a new Folder in the project of the name Repository and add the following interface and a class in this folder:

//Product.cs
public class Product
{
 public int Id { get; set; }
 public string Name { get; set; }
 public string Category { get; set; }
 public decimal Price { get; set; }
}

//IProductRepository.cs
public interface IProductRepository
{
 IEnumerable<Product> GetAll();
 Product Get(int id);
 Product Add(Product item);
 bool Update(Product item);
 bool Delete(int id);
}

//ProductRepository.cs
public class ProductRepository : IProductRepository
{
 private List<Product> products = new List<Product>();
 private int _nextId = 1;

 public ProductRepository()
 {
 // Add products for the Demonstration
 Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
 Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
 Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
 }

 public IEnumerable GetAll()
 {
 // TO DO : Code to get the list of all the records in database
 return products;

 }

 public Product Get(int id)
 {
 // TO DO : Code to find a record in database
 return products.Find(p => p.Id == id);

 }

 public Product Add(Product item)
 {
 if (item == null)
 {
 throw new ArgumentNullException("item");
 }
 
 // TO DO : Code to save record into database
 item.Id = _nextId++;
 products.Add(item);

 return item;
 }

 public bool Update(Product item)
 {
 if (item == null)
 {
 throw new ArgumentNullException("item");
 }
 
 // TO DO : Code to update record into database
 int index = products.FindIndex(p => p.Id == item.Id);
 if (index == -1)
 {
 return false;
 }
 products.RemoveAt(index);
 products.Add(item);

 return true;
 }

 public bool Delete(int id)
 {
 // TO DO : Code to remove the records from database
 products.RemoveAll(p => p.Id == id);

 return true;
 }
}

The above repository acts as a new layer and will be used to decouple the model layer from the controller layer.

Step 4- Register the Dependency in Bootstrapper.cs file

Replace BuildUnityContainer method's content with the following code that registers the ProductRepository Service. You can also register the Product Controller in which we will inject the dependency, but it is optional.

private static IUnityContainer BuildUnityContainer()
{
 var container = new UnityContainer();

 // register all your components with the container here
 // it is NOT necessary to register your controllers

 container.RegisterType<IProductRepository, ProductRepository>();
 
 // e.g. container.RegisterType<ITestService, TestService>(); 
 
 RegisterTypes(container);

 return container;
}

Step 5- Inject Service to Controller

Now inject the dependency for the IProductRepository interface using the Product Controller's constructor as shown below:

public class ProductController : Controller
{
 readonly IProductRepository repository;

 //inject dependency
 public ProductController(IProductRepository repository)
 {
 this.repository = repository; 
 }

 public ActionResult Index()
 {
 var data = repository.GetAll();
 return View(data);
 }
 //Other Code
}

Step 6 – Setup Dependency Injection with Unity in Global.asax.cs

Now, setup the Bootstrapper class with in the Application_Start method so that it can initialize all dependencies. This will be done by calling Initialise() method of the Bootstrapper class as shown below:

protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();

 WebApiConfig.Register(GlobalConfiguration.Configuration);
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 AuthConfig.RegisterAuth();
 
 //Setup DI
 Bootstrapper.Initialise();
}

Step 7- Run the Application and see how it works

What do you think?

I hope you will enjoy the tips while programming with Asp.Net MVC4. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.



ABOUT AUTHOR

Shailendra Chauhan
Author, Architect, Corporate Trainer and Microsoft MVP

He is the author of some of most popular e-books which encompass technical Interview on Node.js Interview Questions and Answers, ASP.NET MVC Interview Questions and Answers, AngularJS Interview Questions and Answers and LINQ Interview Questions and AnswersKnow more...

Free Interview Books
 
COMMENTS (3)
Kannan P Reply

nice article. really loved it.

Nishil Athikkal Reply

can you please explain what is the use of "public static void RegisterTypes(IUnityContainer container){}" method ??

liu yufang Reply

super article ! I download your code, but i think you have juste missed the Product action in the ProductController so that when i click Product actionlink make the error page PS: the party ProcuctViewModel in Product.cshtml is so mysterious....

5 AUG
ASP.NET MVC with Angular4 Development (Online)

10:30 Am to 12:30 PM IST (+ 5:30 GMT)

Know More
3 AUG
ASP.NET Core with Angular4 Development (Online)

07:00 AM - 9:00 AM IST(+5:30 GMT)

Know More
29 JUL
Angular2 and Angular4 Development (Online)

08:00 AM - 10:00 AM IST(+5.30 GMT)

Know More
29 JUL
ASP.NET MVC with Angular4 Development (Classroom)

09:30 AM - 11:00 AM IST (+5:30GMT)

Know More
29 JUL
Xamarin Forms : Build Cross-platform Apps (Classroom)

09:00 AM - 11:00 AM IST(+5:30 GMT)

Know More
26 JUL
ASP.NET MVC with Angular4 Development (Online)

07:00 AM - 09:00 AM IST(+5.30 GMT)

Know More
26 JUL
ASP.NET MVC with Angular4 Development (Online)

07:00 AM - 09:00 AM IST(+5.30 GMT)

22 JUL
MEAN Stack 2 Development (Classroom)

04:00 PM - 05:30 PM IST(+5:30GMT)

20 JUL
Hadoop Development cum Administration (Online)

07:00 AM - 09:00 AM IST(+5:30 GMT)

17 JUL
NodeJS with Angular4 Development (Online)

08:00 PM - 09:30 PM IST(+5.30 GMT)

15 JUL
ASP.NET MVC with Angular4 Development (Online)

03:30 PM - 05:30 PM IST(+5.30 GMT)

1 JUL
ASP.NET MVC with Angular4 Development (Classroom)

08:00 AM - 09:30 AM IST

1 JUL
MEAN Stack 2 Development (Classroom)

11:00 AM - 12:30 PM IST(+5:30 GMT)

30 JUN
Xamarin Forms : Build Cross-platform Apps (Online)

09:30 PM - 11:00PM IST(+5:30GMT)

6 JUN
ASP.NET MVC with Angular4 Development (Online)

09:00 PM-11:00 PM IST(+5.30 GMT)

20 MAY
NodeJS with Angular4 Development (Classroom)

05:00 PM - 07:00 PM

2 MAY
ASP.NET Core Development (Online)

07:00 AM - 09:00 AM IST(+5.30 GMT)

BROWSE BY CATEGORY
 
 
LIKE US ON FACEBOOK
 
+