Implement IoC Using Unity in MVC 5

This article explains a very important concept called IoC and to implement IoC we will use Unity which is an IoC container released by Microsoft.

This article assumes a basic understanding of the de-coupled architecture and Inversion of Control (IoC) principal. If you are very new in both concepts I recommend you understand both first. We all know that the de-coupled architecture is one of the major goals of a good design pattern in applications and Inversion of Control is the way to do that. As the name Inversion of control suggests, we will redirect the control follow in a reverse order to implement de-coupled architecture.

There are the following two implementations of Inversion of Control:

  1. Dependency Injection
  2. Service locator.

In this example we will implement Dependency Injection using Unity within a MVC5 application. So, to follow this article I suggest you create an Empty MVC 5 application and install the following packages from the NuGet Package Manager.

Please note that Unity is a product from Microsoft and it will help us to create a repository of dependency classes that will be pluggable in mode. In other words, the main advantage of Unity is that if needed we can just plug it in with another application.

Use the following procedure to install the following packages:



Once installed successfully you will find that the following assembly has been added to the application.



Step 1: Create Unity container

Fine, we will now add a Bootstrapper class to the application. Take one .cs file and modify it accordingly.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using DITest.Repository;  
  7. using Microsoft.Practices.Unity;  
  8. using Microsoft.Practices.Unity.Mvc;  
  9.   
  10. namespace DITest  
  11. {  
  12.     public class Bootstrapper  
  13.     {  
  14.         public static IUnityContainer Initialise()  
  15.         {  
  16.             var container = BuildUnityContainer();  
  17.             DependencyResolver.SetResolver(new UnityDependencyResolver(container));  
  18.             return container;  
  19.         }  
  20.         private static IUnityContainer BuildUnityContainer()  
  21.         {  
  22.             var container = new UnityContainer();  
  23.   
  24.             // register all your components with the container here  
  25.             //This is the important line to edit  
  26.             container.RegisterType<ICompanyRepository, CompanyRepository>();   
  27.   
  28.   
  29.             RegisterTypes(container);  
  30.             return container;  
  31.         }  
  32.         public static void RegisterTypes(IUnityContainer container)  
  33.         {  
  34.   
  35.         }  
  36.     }  
  37. }  
This is the Bootstrapper class to be implemented to create a container of dependency objects. Please note that we have added the following lines:
  1. container.RegisterType<ICompanyRepository, CompanyRepository>();  
To the BuildUnityContainer() function. The line is to register the Interface and it's implementation in the container, we will create both shortly.

Step 2 : Register container class

We will now register the container class in the global.aspx page. Here is the screen of my global.aspx page.



This single highlighted line will register the Unity container in the application.

Step 3 : Create class /Model

We will now create the model/class. In this example I have decided to implement one “company” class, that will hold a few eices of company information. The definition is as in the following.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace DITest.Repository  
  7. {  
  8.     public class Company  
  9.     {  
  10.         public int Id { getset; }  
  11.         public string Name { getset; }  
  12.         public string Category { getset; }  
  13.     }  
  14. }  
It's simple, just three properties. In reality it could contain many properties or if you are using Entity Framework then by default, the model will be created for you.

I recommend you create a folder called “Repository” in the solution and keep the model in that place, because in the future we will add two more classes to deal with the mode.

Step 4 : Create Interface

Create one IProductRepository.cs file in the “Repository” folder and modify the code accordingly as in the following:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace DITest.Repository  
  7. {  
  8.     public interface ICompanyRepository  
  9.     {  
  10.        IEnumerable<Company> GetAll();  
  11.        Company Get(int id);  
  12.        Company Add(Company item);  
  13.        bool Update(Company item);  
  14.        bool Delete(int id);  
  15.     }  
  16. }  
We are seeing that the interface is targeting CRUD operations over the collection. When we call the GetAll() function it will return a collection of “Company” information. It will help us to implement the de-coupled architecture in the application. Very shortly we will implement it in the Repository class.

Step 5 : Implement interface in CompanyRepository.cs file

We will now implement the interface in the actual class. So, we will create a CompanyRepository.cs file within “Repository” older and modify it accordingly. The implementation is very easy to understand, since we are just doing CRUD operations on the Company list. All functions and it's operations are self-defined.
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace DITest.Repository  
  8. {  
  9.     public class CompanyRepository : ICompanyRepository  
  10.     {  
  11.         private List<Company> products = new List<Company>();  
  12.         private int _nextId = 1;  
  13.   
  14.         public CompanyRepository()  
  15.         {  
  16.             // Add products for the Demonstration  
  17.             Add(new Company { Name = "TIMKEN Eng", Category = "Engenering"});  
  18.             Add(new Company { Name = "Wipro", Category = "software"});  
  19.             Add(new Company { Name = "HSBC", Category = "Bank"});  
  20.         }  
  21.   
  22.         public IEnumerable<Company> GetAll()  
  23.         {  
  24.             // TO DO : Code to get the list of all the records in database  
  25.             return products;  
  26.         }  
  27.         public Company Get(int id)  
  28.         {  
  29.             // TO DO : Code to find a record in database  
  30.             return products.Find(p => p.Id == id);  
  31.         }  
  32.         public Company Add(Company item)  
  33.         {  
  34.             if (item == null)  
  35.             {  
  36.                 throw new ArgumentNullException("item");  
  37.             }  
  38.   
  39.             // TO DO : Code to save record into database  
  40.             item.Id = _nextId++;  
  41.             products.Add(item);  
  42.             return item;  
  43.         }  
  44.         public bool Update(Company item)  
  45.         {  
  46.             if (item == null)  
  47.             {  
  48.                 throw new ArgumentNullException("item");  
  49.             }  
  50.   
  51.             // TO DO : Code to update record into database  
  52.             int index = products.FindIndex(p => p.Id == item.Id);  
  53.             if (index == -1)  
  54.             {  
  55.                 return false;  
  56.             }  
  57.             products.RemoveAt(index);  
  58.             products.Add(item);  
  59.             return true;  
  60.         }  
  61.         public bool Delete(int id)  
  62.         {  
  63.             // TO DO : Code to remove the records from database  
  64.             products.RemoveAll(p => p.Id == id);  
  65.             return true;  
  66.         }  
  67.     }   
  68. }  
Step 6 : Add controller class to the application

We will now add one controller class and from there we will consume the data of the Company model. Here is the controller class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using DITest.Repository;  
  7. using Newtonsoft.Json;  
  8.   
  9. namespace DITest.Controllers  
  10. {  
  11.     public class CompanyController : Controller  
  12.     {  
  13.         readonly ICompanyRepository repo;  
  14.         public CompanyController(ICompanyRepository tempProduct)  
  15.         {  
  16.             this.repo = tempProduct;  
  17.         }  
  18.         public string Index()  
  19.         {  
  20.             var data = repo.GetAll();  
  21.             return JsonConvert.SerializeObject(data);  
  22.         }  
  23.     }  
  24. }  
If you observe the controller class, you will find that we are not creating an object of a concrete class within the controller, we are using an ICompanyRepository interface.

From the Index() action I am interested in returning a JSON result , since I am not using any view, so I can consume the result in Fiddler.



Conclusion

 

We have now seen how to implement IoC using the Unity framework. I hope this will help to implement the de-coupled architecture in your application. The great advantage of Unity is, it's a container and once you register our object within the container, you can use it anywhere.