HI WELCOME TO SIRIS

Dependency Injection in ASP.NET MVC using Unity IoC Container

In the previous articles, I have explained about the Understanding IoC, DI and Service Locator Pattern and IoC or DI Containers. Before proceeding with this article, please go through my last articles. In this article, you will learn how to use Unity DI Container in your ASP.NET MVC application to make the service layer and Presentation layer loosely coupled.

Step 1 - Create a new ASP.NET MVC Application

First step is to create a new ASP.NET MVC Application using Visual Studio 2012 or higher as shown below:

Step 2- Install Unity Container

Now install Unity container using Unity.Mvc4 (for MVC4) or Unity.Mvc5 (for MVC5) nuget package as per your ASP.NET MVC versions, using the NuGet Package Manager console tool as shown below:


Note

Make sure you are connected with internet.
When it will be installed successfully, you will be find the following two references add to your project and a Bootstrapper.cs class file in MVC4 and UnityConfig.cs file in MVC5 at project level, as shown below:


  1. //mvc4
  2. using System.Web.Mvc;
  3. using Microsoft.Practices.Unity;
  4. using Unity.Mvc4;
  5.  
  6. namespace MvcNUnit
  7. {
  8. public static class Bootstrapper
  9. {
  10. public static IUnityContainer Initialise()
  11. {
  12. var container = BuildUnityContainer();
  13. DependencyResolver.SetResolver(new UnityDependencyResolver(container));
  14. return container;
  15. }
  16. private static IUnityContainer BuildUnityContainer()
  17. {
  18. var container = new UnityContainer();
  19. // register all your components with the container here
  20. // it is NOT necessary to register your controllers
  21. // e.g. container.RegisterType<ITestService, TestService>();
  22. RegisterTypes(container);
  23. return container;
  24. }
  25. public static void RegisterTypes(IUnityContainer container)
  26. {
  27. }
  28. }
  29. }
  1. //mvc5
  2. using BAL;
  3. using System.Web.Mvc;
  4. using Unity;
  5. using Unity.Mvc5;
  6.  
  7. namespace UI
  8. {
  9. public static class UnityConfig
  10. {
  11. public static void RegisterComponents()
  12. {
  13. var container = new UnityContainer();
  14.  
  15. // register all your components with the container here
  16. // it is NOT necessary to register your controllers
  17.  
  18. // e.g. container.RegisterType<ITestService, TestService>();
  19. DependencyResolver.SetResolver(new UnityDependencyResolver(container));
  20. }
  21. }
  22. }

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:
  1. //Product.cs
  2. public class Product
  3. {
  4. public int Id { get; set; }
  5. public string Name { get; set; }
  6. public string Category { get; set; }
  7. public decimal Price { get; set; }
  8. }
  9.  
  10. //IProductRepository.cs
  11. public interface IProductRepository
  12. {
  13. IEnumerable<Product> GetAll();
  14. Product Get(int id);
  15. Product Add(Product item);
  16. bool Update(Product item);
  17. bool Delete(int id);
  18. }
  19.  
  20. //ProductRepository.cs
  21. public class ProductRepository : IProductRepository
  22. {
  23. private List<Product> products = new List<Product>();
  24. private int _nextId = 1;
  25.  
  26. public ProductRepository()
  27. {
  28. // Add products for the Demonstration
  29. Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
  30. Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
  31. Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
  32. }
  33.  
  34. public IEnumerable GetAll()
  35. {
  36. // TO DO : Code to get the list of all the records in database
  37. return products;
  38. }
  39. public Product Get(int id)
  40. {
  41. // TO DO : Code to find a record in database
  42. return products.Find(p => p.Id == id);
  43. }
  44. public Product Add(Product item)
  45. {
  46. if (item == null)
  47. {
  48. throw new ArgumentNullException("item");
  49. }
  50. // TO DO : Code to save record into database
  51. item.Id = _nextId++;
  52. products.Add(item);
  53. return item;
  54. }
  55. public bool Update(Product item)
  56. {
  57. if (item == null)
  58. {
  59. throw new ArgumentNullException("item");
  60. }
  61. // TO DO : Code to update record into database
  62. int index = products.FindIndex(p => p.Id == item.Id);
  63. if (index == -1)
  64. {
  65. return false;
  66. }
  67. products.RemoveAt(index);
  68. products.Add(item);
  69. return true;
  70. }
  71. public bool Delete(int id)
  72. {
  73. // TO DO : Code to remove the records from database
  74. products.RemoveAll(p => p.Id == id);
  75. return true;
  76. }
  77. }
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 or UnityConfig.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.
  1. private static IUnityContainer BuildUnityContainer()
  2. {
  3. var container = new UnityContainer();
  4.  
  5. // register all your components with the container here
  6. // it is NOT necessary to register your
  7. // e.g. container.RegisterType<ITestService, TestService>();
  8.  
  9. //registered dependency here
  10. container.RegisterType<IProductRepository, ProductRepository>();
  11. RegisterTypes(container);
  12.  
  13. return container;
  14. }
  1. //mvc5
  2. using BAL;
  3. using System.Web.Mvc;
  4. using Unity;
  5. using Unity.Mvc5;
  6.  
  7. namespace UI
  8. {
  9. public static class UnityConfig
  10. {
  11. public static void RegisterComponents()
  12. {
  13. var container = new UnityContainer();
  14.  
  15. // register all your components with the container here
  16. // it is NOT necessary to register your controllers
  17.  
  18. // e.g. container.RegisterType<ITestService, TestService>();
  19.  
  20. //registered dependency here
  21. container.RegisterType<IUnitOfWork, UnitOfWork>();
  22.  
  23. DependencyResolver.SetResolver(new UnityDependencyResolver(container));
  24. }
  25. }
  26. }

Step 5- Inject Service to Controller

Now inject the dependency for the IProductRepository interface using the Product Controller's constructor as shown below:
  1. public class ProductController : Controller
  2. {
  3. readonly IProductRepository repository;
  4.  
  5. //inject dependency
  6. public ProductController(IProductRepository repository)
  7. {
  8. this.repository = repository;
  9. }
  10.  
  11. public ActionResult Index()
  12. {
  13. var data = repository.GetAll();
  14. return View(data);
  15. }
  16. //Other Code
  17. }

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

Now, setup the Bootstrapper or UnityConfig 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 or RegisterComponents() methods of UnityConfig.cs class as shown below:
  1. //mvc4
  2. protected void Application_Start()
  3. {
  4. AreaRegistration.RegisterAllAreas();
  5.  
  6. WebApiConfig.Register(GlobalConfiguration.Configuration);
  7. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  8. RouteConfig.RegisterRoutes(RouteTable.Routes);
  9. BundleConfig.RegisterBundles(BundleTable.Bundles);
  10. AuthConfig.RegisterAuth();
  11. //Setup DI
  12. Bootstrapper.Initialise();
  13. }
  1. //mvc5
  2. protected void Application_Start()
  3. {
  4. AreaRegistration.RegisterAllAreas();
  5. // Setup DI
  6. UnityConfig.RegisterComponents();
  7. RouteConfig.RegisterRoutes(RouteTable.Routes);
  8. }

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 MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.