濮阳杆衣贸易有限公司

主頁 > 知識庫 > 剖析ASP.NET MVC的DependencyResolver組件

剖析ASP.NET MVC的DependencyResolver組件

熱門標(biāo)簽:地圖標(biāo)注的公司有哪些 塔城代理外呼系統(tǒng) 代理接電話機器人如何取消 400電話辦理哪家性價比高 遂寧市地圖標(biāo)注app 地圖定位圖標(biāo)標(biāo)注 地圖標(biāo)注專業(yè)團隊 天心智能電銷機器人 濮陽外呼電銷系統(tǒng)怎么樣

一、前言

  DependencyResolver是MVC中一個重要的組件,從名字可以看出,它負(fù)責(zé)依賴對象的解析,可以說它是MVC框架內(nèi)部使用的一個IOC容器。MVC內(nèi)部很多對象的創(chuàng)建都是通過它完成的,或許我們平時沒有直接用到它,但是如果你在使用unity、autofac,或者在看一些開源項目時,總會看到它的身影。接下來就讓我們看一下這個組件是如何工作的。

二、通過Controller的激活理解DependencyResolver的工作過程

  這里先插一個題外話,經(jīng)常會有面試問:asp.net 幾個核心對象是什么?一般人都會回答:Server、Request、Response、Session、Cookie這些。但我的回答會是HttpApplication、HttpHandler和HttpModule,這才是管道模型中的核心類型,整個asp.net的處理流程和可擴展性也都是建立在這幾個對象上的。

  回到主題,asp.net請求都是交給HttpHandler處理的,對于MVC來說,是交給一個MvcHandler,它負(fù)責(zé)激活Controller,如果你不知道為什么,請看這里。在這里我們直接定位到MvcHandler的PR方法:

protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
{
  IController controller;
  IControllerFactory factory;
  ProcessRequestInit(httpContext, out controller, out factory);
 
  //其它操作
  //調(diào)用 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,默認(rèn)就是DefaultControllerFactory
  factory = ControllerBuilder.GetControllerFactory();
 
  //通過ControllerFactory獲取Controller對象
  controller = factory.CreateController(RequestContext, controllerName);
}

  ControllerFactory故名思議就是用于創(chuàng)建Controller的,我們也可以自己實現(xiàn)IControllerFactory,參與Controller的激活過程,具體是在全局調(diào)用ControllerBuilder.Current.SetControllerFactory方法。我們這里主要關(guān)注的是Controller的激活過程,實際上它們的創(chuàng)建過程是相似的。默認(rèn)使用的ControllerFactory是DefaultControllerFactory。DefaultControllerFactory的CreateController方法如下:  

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來創(chuàng)建IController對象,默認(rèn)使用的是DefaultControllerActivator。與ControllerFactory類似,我們可以實現(xiàn)IControllerActivator,參與Controller的激活過程,具體是將ControllerActivator作為DefaultConrtollerFactory構(gòu)造函數(shù)參數(shù),然后再在全局調(diào)用ControllerBuilder.Current.SetControllerFactory方法??梢钥吹組VC的Controller激活過程是很靈活的,它提供多種方式讓我們自定義激活過程。DefaultControllerActivator定義如下:

private class DefaultControllerActivator : IControllerActivator
{
  private FuncIDependencyResolver> _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。我們也可以自己實現(xiàn)IDependencyResolver,參與Controller的激活過程,具體是在全局調(diào)用DependencyResolver的靜態(tài)方法SetResolver方法。需要注意的是這里的DependencyResolver類型(這里是類型,而其它地方提到的DependencyResolver都是組件的意思)并沒有實現(xiàn)IDependencyResolver接口,我覺得將它命名為DependencyResolverContainer會更合適一些。IDepdencyResolver接口的定義如下:

public interface IDependencyResolver
{
  object GetService(Type serviceType);
  IEnumerableobject> GetServices(Type serviceType);
}

  默認(rèn)DependencyResolver.Current使用的是DefaultDependencyResolver類型,這里又和ControllerFactory和ControllerActivator的設(shè)計一樣了,如果我們自定義,那么就使用,否則就使用默認(rèn)的。DefaultDependencyResolver定義如下:

private class DefaultDependencyResolver : IDependencyResolver
{
  public object GetService(Type serviceType)
  {
    if (serviceType.IsInterface || serviceType.IsAbstract)
    {
      return null;
    }
 
    try
    {
      //如果Controller Type創(chuàng)建Controller實例對象
      return Activator.CreateInstance(serviceType);
    }
    catch
    {
      return null;
    }
  }
 
  public IEnumerableobject> GetServices(Type serviceType)
  {
    return Enumerable.Emptyobject>();
  }
}

  可以看到,MVC會將Controller對象的創(chuàng)建通過DependencyResolver完成。將對象的創(chuàng)建通過DependencyResolver完成的好處是可以降低對象間的耦合度;另外,通過實現(xiàn)IDependencyResolver接口,我們可以完全控制對象的創(chuàng)建過程,例如將對象的依賴關(guān)系轉(zhuǎn)移到配置文件中等等。

  通過上面我們還知道了有三種默認(rèn)類型:DefaultControllerFactory、DefaultControllerActivator和DefaultDependencyResolver,分別對應(yīng)三個接口:IControllerFactory、IControllerActivator、IDependencyResolver。它們的設(shè)計是類似的,都是提供給外部一個接口,如果外部自己實現(xiàn)了這個過程,那么就使用,否則用默認(rèn)的。實際上這也是我們參與Controller激活過程的三種做法。

三、實現(xiàn)IDependencyResolver接口

  接下來通過一個例子證明上面的過程。我們要實現(xiàn)的需求是通過實現(xiàn)IDependencyResolver接口,實現(xiàn)Controller構(gòu)造函數(shù)注入服務(wù)。如:

public class HomeController : Controller
{      
  private IUserService _service;
  public HomeController(IUserService service)
  {
    _service = service;
  }
 
  public ActionResult Index()
  {
    return Content(_service.GetUserName());
  }
}


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

  接下來我們實現(xiàn)IDependencyResolver接口,依賴注入的實現(xiàn)方式有很多種,這里我們使用Unity。如下:

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 IEnumerableobject> 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內(nèi)部很多對象都是通過DependencyResolver組件創(chuàng)建的,如上面的IConrtollerFactoy,所以這里我們只負(fù)責(zé)對已注冊的類型或類(非抽象類)進(jìn)行解析。

  Ioc類在這里很簡單,如下:

public class Ioc
{
  private static IUnityContainer _container = new UnityContainer();
 
  public static void RegisterTypeTFrom,TTo>()
    where TTo : TFrom
  {      
    _container.RegisterTypeTFrom, TTo>();
  }
 
  public static object GetService(Type type)
  {            
    return _container.Resolve(type);
  }
 
  public static IEnumerableobject> GetServices(Type type)
  {
    return _container.ResolveAll(type);
  }
 
  public static bool IsRegistered(Type type)
  {
    return _container.IsRegistered(type);
  }
}

接著,在Application_Start方法中,注冊Service和設(shè)置IocDependencyResolver:

Ioc.RegisterTypeIUserService, UserService>();
DependencyResolver.SetResolver(new IocDependencyResolver());
  運行就可以看到HomeController構(gòu)造函數(shù)的IUserService就是UserService類型了。

四、總結(jié)

   實際上,上面的例子我們也可以用實現(xiàn)IControllerFactory或者IControllerActivator達(dá)到同樣的目的,但使用IDependencyResolver會更簡單一點,而且大部分的IOC框架都已經(jīng)提供了這樣的功能。例如上面UnityDependencyResolver根本不用自己定義,Unity for MVC 已經(jīng)有這么一個類型了,直接使用即可。如果使用Autofac的話可以是:DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。

您可能感興趣的文章:
  • Springboot視圖解析器ViewResolver使用實例
  • 淺談SpringMVC之視圖解析器(ViewResolver)
  • MultipartResolver實現(xiàn)文件上傳功能
  • springboot+thymeleaf國際化之LocaleResolver接口的示例
  • android利用ContentResolver訪問者獲取手機短信信息
  • spring-core組件詳解——PropertyResolver屬性解決器
  • Nginx DNS resolver配置實例
  • Springmvc ViewResolver設(shè)計實現(xiàn)過程解析

標(biāo)簽:汕頭 本溪 重慶 婁底 吉林 宜春 河南 麗江

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《剖析ASP.NET MVC的DependencyResolver組件》,本文關(guān)鍵詞  剖析,ASP.NET,MVC,的,DependencyResolver,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《剖析ASP.NET MVC的DependencyResolver組件》相關(guān)的同類信息!
  • 本頁收集關(guān)于剖析ASP.NET MVC的DependencyResolver組件的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    资阳市| 礼泉县| 郴州市| 沅陵县| 温宿县| 满城县| 大名县| 湟源县| 彩票| 靖西县| 商河县| 朝阳区| 灵台县| 平潭县| 香港| 靖西县| 扶余县| 湖南省| 巴马| 靖宇县| 全南县| 东明县| 遂溪县| 自治县| 彝良县| 江津市| 项城市| 云和县| 桦甸市| 科技| 麻栗坡县| 仪陇县| 咸丰县| 木兰县| 遂宁市| 临朐县| 秀山| 阿城市| 得荣县| 镇江市| 北流市|