微软的依赖注入容器,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
 
 
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<CustomerController>();  
  24.             objContainer.RegisterType<ICustomer, Customer>();  
  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 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Over the years software systems have evolutionarily become more and more complex. One of the techniques for dealing with this inherent complexity of software systems is dependency injection – a design pattern that allows the removal of hard-coded dependencies and makes it possible to assemble a service by changing dependencies easily, whether at run-time or compile-time. It promotes code reuse and loosely-coupled design which leads to more easily maintainable and flexible code. The guide you are holding in your hands is a primer on using dependency injection with Unity – a lightweight extensible dependency injection container built by the Microsoft patterns & practices team. It covers various styles of dependency injection and also additional capabilities of Unity container, such as object lifetime management, interception, and registration by convention. It also discusses the advanced topics of enhancing Unity with your custom extensions. The guide contains plenty of trade-off discussions and tips and tricks for managing your application cross-cutting concerns and making the most out of both dependency injection and Unity. These are accompanied by a real world example that will help you master the techniques. Keep in mind that Unity can be used in a wide range of application types such as desktop, web, services, and cloud. We encourage you to experiment with the sample code and think beyond the scenarios discussed in the guide. In addition, the guide includes the Tales from the Trenches – a collection of case studies that offer a different perspective through the eyes of developers working on the real world projects and sharing their experiences. These chapters make clear the range of scenarios in which you can use Unity, and also highlight its ease of use and flexibility. Whether you are a seasoned developer or just starting your development journey, we hope this guide will be worth your time studying it. We hope you discover that Unity container adds significant benefits to your applications and helps you to achieve the goals of maintainability, testability, flexibility, and extensibility in your own projects.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值