微软的依赖注入容器,Unity

In this article i am going to explain how to use Dependency Injection(DI) in MVC application. 
 

Dependency injection (DI) design pattern is based on separating component behavior from dependency resolution without object intervention. This pattern is a particular implementation of Inversion of Control, where the consumer object receives his dependencies inside constructor properties or arguments.DI requires a framework component behind to deal with class constructor. 

 
 
 
  The advantages of using Dependency Injection pattern and Inversion of Control are the following:
  • Reduces class coupling
  • Increases code reusing
  • Improves code maintainability
  • Improves application testing
Please remember  Depencency Injection is sometimes compared with Abstract Factory Design Pattern, but there is a slight difference between both approaches. DI has a Framework working behind to solve dependencies by calling the factories and the registered services.
 
We can inject DI in MVC in 3 ways.   
  • Use dependency injection inside an MVC Controller
  • Use dependency injection inside an MVC View
  • Use dependency injection inside an MVC Action Filter
In this article i will cover DI inside a MVC Controller and remaining 2 shall be covered in the coming article.
 
I am going to use Unity Application Block as the dependency resolver framework, but it is possible to adapt any Dependency Injection Framework to work with MVC 3 or 4.  
 
Steps1: Download Unity Application Block from msdn
 
http://www.microsoft.com/en-in/download/details.aspx?id=19372
 
Steps2: Create a very simple MVC 3.0 application. 
 
 
 
You can see in the above figure i created a separate folder "Dependency Resolved". I will explain later why this is created.
 
Step3: Add the unity application block dll's in your solution.
 
 
 
Step:4- Create a very simple model called Customer like below
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace DependencyInjectionwithMVC.Models  
  7. {  
  8.     public class Customer : ICustomer  
  9.     {  
  10.   
  11.       private string _CustomerName;  
  12.       public string GetCustomerDetails(int customerId)  
  13.         {  
  14.             return "This is Joshi from CGI " + customerId.ToString() + " ";  
  15.         }  
  16.   
  17.       public string customerName  
  18.       {  
  19.           get  
  20.           {  
  21.               return _CustomerName; ;  
  22.           }  
  23.           set  
  24.           {  
  25.               _CustomerName = value;  
  26.           }  
  27.       }  
  28.        
  29.     }  
  30.   
  31.     public interface ICustomer  
  32.     {  
  33.           
  34.          string GetCustomerDetails(int customerId);  
  35.          string customerName { getset; }  
  36.            
  37.     }  
  38.       
  39. }  
Step:5- Add a new class file under DependencyResolver folder like below
 
 
IDependencyResolver  Defines the methods that simplify service location and dependency resolution.  Implementations of this interface should delegate to the underlying dependency injection container to provide the registered service for the requested type. When there are no registered services of the requested type, the ASP.NET MVC framework expects implementations of this interface to return null from GetService and to return an empty collection from GetServices.
 
Here is the implementation 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using Microsoft.Practices.Unity;  
  7. namespace DependencyInjectionwithMVC.DependencyResolver  
  8. {  
  9.     public class CustomDependencyResolver : IDependencyResolver  
  10.     {  
  11.   
  12.         readonly IUnityContainer _Container;  
  13.         public CustomDependencyResolver(IUnityContainer objContainer)  
  14.         {  
  15.             _Container = objContainer;  
  16.         }  
  17.         public object GetService(Type serviceType)  
  18.         {  
  19.             if (!_Container.IsRegistered(serviceType))  
  20.             {  
  21.                 return null;  
  22.             }  
  23.   
  24.             return _Container.Resolve(serviceType);  
  25.         }  
  26.   
  27.         public IEnumerable<object> GetServices(Type serviceType)  
  28.         {  
  29.             if (!_Container.IsRegistered(serviceType))  
  30.             {  
  31.                 return new List<object>();  
  32.             }  
  33.   
  34.             return _Container.ResolveAll(serviceType);  
  35.         }  
  36.   
  37.          
  38.     }  
  39. }  
Step6: Make some minor changes in Global.ascx file under Application_Start()method. Also you have to refer below highlighted namespaces as well in the Global.ascx file. 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Http;  
  6. using System.Web.Mvc;  
  7. using System.Web.Routing;  
  8. using Microsoft.Practices.Unity;  
  9. using DependencyInjectionwithMVC.Controllers;  
  10. using DependencyInjectionwithMVC.Models;  
  11. using DependencyInjectionwithMVC.DependencyResolver;  
  12. namespace DependencyInjectionwithMVC  
  13. {  
  14.     // Note: For instructions on enabling IIS6 or IIS7 classic mode,   
  15.     // visit http://go.microsoft.com/?LinkId=9394801  
  16.     public class MvcApplication : System.Web.HttpApplication  
  17.     {  
  18.         protected void Application_Start()  
  19.         {  
  20.             AreaRegistration.RegisterAllAreas();  
  21.   
  22.             IUnityContainer objContainer = new UnityContainer();  
  23.             objContainer.RegisterType();  
  24.             objContainer.RegisterType();  
  25.             System.Web.Mvc.DependencyResolver.SetResolver(new CustomDependencyResolver(objContainer));  
  26.             WebApiConfig.Register(GlobalConfiguration.Configuration);  
  27.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  28.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  29.         }  
  30.     }  
  31. }  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using DependencyInjectionwithMVC.Models;  
  7.   
  8. namespace DependencyInjectionwithMVC.Controllers  
  9. {  
  10.     public class CustomerController : Controller  
  11.     {  
  12.         private ICustomer objCustomer;  
  13.         public CustomerController(ICustomer Customer)  
  14.         {  
  15.             objCustomer = Customer;    
  16.         }  
  17.         public ActionResult Index()  
  18.         {  
  19.             objCustomer.customerName = objCustomer.GetCustomerDetails(123);  
  20.               
  21.             return View("Index",objCustomer);  
  22.         }  
  23.   
  24.     }  
  25. }  
Now we can inject ICustomer in to the constructor of my controller class very easily.
 
Here you go with the result 
 
 
I hope you now you understand how to inject a DI in to the constructor of your controller class 

你可能感兴趣的:(.NET)