理解ASP.NET MVC的DependencyResolver組件

1、前言html

   DependencyResolver是MVC中一個重要的組件,從名字能夠看出,它負責依賴對象的解析,能夠說它是MVC框架內部使用的一個IOC容 器。MVC內部不少對象的建立都是經過它完成的,或許咱們平時沒有直接用到它,可是若是你在使用unity、autofac,或者在看一些開源項目時,總 會看到它的身影。接下來就讓咱們看一下這個組件是如何工做的。面試

2、經過Controller的激活理解DependencyResolver的工做過程框架

   這裏先插一個題外話,常常會有面試問:asp.net 幾個核心對象是什麼?通常人都會回答:Server、Request、Response、Session、Cookie這些。但個人回答會是 HttpApplication、HttpHandler和HttpModule,這纔是管道模型中的核心類型,整個asp.net的處理流程和可擴展性 也都是創建在這幾個對象上的。asp.net

  回到主題,asp.net請求都是交給HttpHandler處理的,對於MVC來講,是交給一個MvcHandler,它負責激活Controller,若是你不知道爲何,請看這裏。在這裏咱們直接定位到MvcHandler的PR方法:函數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected  internal  virtual  IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback,  object  state)
{
     IController controller;
     IControllerFactory factory;
     ProcessRequestInit(httpContext,  out  controller,  out  factory);
 
     //其它操做
     //調用 controller.Execute方法
}
 
private  void  ProcessRequestInit(HttpContextBase httpContext,  out  IController controller,  out  IControllerFactory factory)
{
     HttpContext currentContext = HttpContext.Current;
 
     //從路由獲取controller名稱
     string  controllerName = RequestContext.RouteData.GetRequiredString( "controller" );
 
     //經過ControllerBuilder獲取ControllerFactory,默認就是DefaultControllerFactory
     factory = ControllerBuilder.GetControllerFactory();
 
     //經過ControllerFactory獲取Controller對象
     controller = factory.CreateController(RequestContext, controllerName);
}

  ControllerFactory故名思議就是用於建立Controller的,咱們也能夠本身實現IControllerFactory, 參與Controller的激活過程,具體是在全局調用ControllerBuilder.Current.SetControllerFactory 方法。咱們這裏主要關注的是Controller的激活過程,實際上它們的建立過程是類似的。默認使用的ControllerFactory是DefaultControllerFactory。DefaultControllerFactory的CreateController方法以下:  學習

1
2
3
4
5
6
7
8
9
10
11
12
13
public  virtual  IController CreateController(RequestContext requestContext,  string  controllerName)
{
     //獲取Controller類型
     Type controllerType = GetControllerType(requestContext, controllerName);
 
     IController controller = GetControllerInstance(requestContext, controllerType);
     return  controller;
}
 
protected  internal  virtual  IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
     return  ControllerActivator.Create(requestContext, controllerType);
}

  能夠看到,它經過一個ControllerActivator來建立IController對象,默認使用的是DefaultControllerActivator。與ControllerFactory相似,咱們能夠實現IControllerActivator, 參與Controller的激活過程,具體是將ControllerActivator做爲DefaultConrtollerFactory構造函數參 數,而後再在全局調用ControllerBuilder.Current.SetControllerFactory方法。能夠看到MVC的 Controller激活過程是很靈活的,它提供多種方式讓咱們自定義激活過程。DefaultControllerActivator定義以下:ui

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private  class  DefaultControllerActivator : IControllerActivator
{
     private  Func<IDependencyResolver> _resolverThunk;
 
     public  DefaultControllerActivator()
         this ( null )
     {
     }
 
     public  DefaultControllerActivator(IDependencyResolver resolver)
     {
         if  (resolver ==  null )
         {
             _resolverThunk = () => DependencyResolver.Current;
         }
         else
         {
             _resolverThunk = () => resolver;
         }
     }
 
     public  IController Create(RequestContext requestContext, Type controllerType)
     {
         try
         {
             return  (IController)(_resolverThunk().GetService(controllerType) ?? Activator.CreateInstance(controllerType));
         }
         catch  (Exception ex)
         {
         }
     }
}

  這裏的_resolverThunk是一個用於獲取IDepencyResolver對 象的委託,實際得到的是DependencyResolver.Current。咱們也能夠本身實現IDependencyResolver,參與 Controller的激活過程,具體是在全局調用DependencyResolver的靜態方法SetResolver方法。須要注意的是這裏的 DependencyResolver類型(這裏是類型,而其它地方提到的DependencyResolver都是組件的意思)並無實現 IDependencyResolver接口,我以爲將它命名爲DependencyResolverContainer會更合適一些。 IDepdencyResolver接口的定義以下:this

1
2
3
4
5
public  interface  IDependencyResolver
{
     object  GetService(Type serviceType);
     IEnumerable< object > GetServices(Type serviceType);
}

  默認DependencyResolver.Current使用的是DefaultDependencyResolver類型,這裏又和ControllerFactory和ControllerActivator的設計同樣了,若是咱們自定義,那麼就使用,不然就使用默認的。DefaultDependencyResolver定義以下:spa

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private  class  DefaultDependencyResolver : IDependencyResolver
{
     public  object  GetService(Type serviceType)
     {
         if  (serviceType.IsInterface || serviceType.IsAbstract)
         {
             return  null ;
         }
 
         try
         {
             //若是Controller Type建立Controller實例對象
             return  Activator.CreateInstance(serviceType);
         }
         catch
         {
             return  null ;
         }
     }
 
     public  IEnumerable< object > GetServices(Type serviceType)
     {
         return  Enumerable.Empty< object >();
     }
}

   能夠看到,MVC會將Controller對象的建立經過DependencyResolver完成。將對象的建立經過 DependencyResolver完成的好處是能夠下降對象間的耦合度;另外,經過實現IDependencyResolver接口,咱們能夠徹底控 制對象的建立過程,例如將對象的依賴關係轉移到配置文件中等等。.net

   經過上面咱們還知道了有三種默認類型:DefaultControllerFactory、DefaultControllerActivator和 DefaultDependencyResolver,分別對應三個接口:IControllerFactory、 IControllerActivator、IDependencyResolver。它們的設計是相似的,都是提供給外部一個接口,若是外部本身實現了 這個過程,那麼就使用,不然用默認的。實際上這也是咱們參與Controller激活過程的三種作法。

3、實現IDependencyResolver接口

  接下來經過一個例子證實上面的過程。咱們要實現的需求是經過實現IDependencyResolver接口,實現Controller構造函數注入服務。如:

1
2
3
4
5
6
7
8
9
10
11
12
13
public  class  HomeController : Controller
{           
     private  IUserService _service;
     public  HomeController(IUserService service)
     {
         _service = service;
     }
 
     public  ActionResult Index()
     {
         return  Content(_service.GetUserName());
     }
}

  HomeController只依賴於IUserService接口,不依賴於具體對象。

  接下來咱們實現IDependencyResolver接口,依賴注入的實現方式有不少種,這裏咱們使用Unity。以下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public  class  UnityDependencyResolver : IDependencyResolver
{
     public  object  GetService(Type serviceType)
     {
         if (serviceType ==  null )
         {
             throw  new  ArgumentNullException( "serviceType" );
         }           
         return  (serviceType.IsClass && !serviceType.IsAbstract)
             || Ioc.IsRegistered(serviceType) ? Ioc.GetService(serviceType) :  null ;
     }
 
     public  IEnumerable< object > GetServices(Type serviceType)
     {
         if  (serviceType ==  null )
         {
             throw  new  ArgumentNullException( "serviceType" );
         }
         return  (serviceType.IsClass && !serviceType.IsAbstract)
             || Ioc.IsRegistered(serviceType) ? Ioc.GetServices(serviceType) :  null ;
     }
}

   這裏須要判斷 (serviceType.IsClass && !serviceType.IsAbstract) || Ioc.IsRegistered(serviceType) 緣由是咱們前面說過的,MVC內部不少對象都是經過DependencyResolver組件建立的,如上面的IConrtollerFactoy,因此 這裏咱們只負責對已註冊的類型或類(非抽象類)進行解析。

  Ioc類在這裏很簡單,以下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public  class  Ioc
{
     private  static  IUnityContainer _container =  new  UnityContainer();
 
     public  static  void  RegisterType<TFrom,TTo>()
         where  TTo : TFrom
     {           
         _container.RegisterType<TFrom, TTo>();
     }
 
     public  static  object  GetService(Type type)
     {                       
         return  _container.Resolve(type);
     }
 
     public  static  IEnumerable< object > GetServices(Type type)
     {
         return  _container.ResolveAll(type);
     }
 
     public  static  bool  IsRegistered(Type type)
     {
         return  _container.IsRegistered(type);
     }
}

  接着,在Application_Start方法中,註冊Service和設置IocDependencyResolver:

1
2
Ioc.RegisterType<IUserService, UserService>();
DependencyResolver.SetResolver( new  IocDependencyResolver());

  運行就能夠看到HomeController構造函數的IUserService就是UserService類型了。

4、總結

    實際上,上面的例子咱們也能夠用實現IControllerFactory或者IControllerActivator達到一樣的目的,但使用 IDependencyResolver會更簡單一點,並且大部分的IOC框架都已經提供了這樣的功能。例如上面 UnityDependencyResolver根本不用本身定義,Unity for MVC 已經有這麼一個類型了,直接使用便可。若是使用Autofac的話能夠是:DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

分享源碼學習:http://www.jinhusns.com/Products/Download/?type=xcj

相關文章
相關標籤/搜索