Asp.net MVC的Controller激活理解

DefaultControllerFactory 是MVC默认的Controller查找和激活工厂类
我们可以通过自定义ControllerFactory替换DefaultControllerFactory类来实现IOC的引入

public class DefaultControllerFactory : IControllerFactory
{
    //其他成员
    public DefaultControllerFactory();
    public DefaultControllerFactory(IControllerActivator controllerActivator);   

}
public interface IControllerActivator//Controller激活器接口
{
     IController Create(RequestContext requestContext, Type controllerType);
}

//此类是DefaultControllerFactory的私有内部类,调用DefaultControllerFactory的默认构造函数或者IControllerActivator参数为null时,默认使用此内部类来激活Controller
private class DefaultControllerActivator : IControllerActivator
{
     private Func<IDependencyResolver> _resolverThunk;用来返回IDependencyResolver实现类的实例
     public DefaultControllerActivator();
    public DefaultControllerActivator(IDependencyResolver resolver);
    public IController Create(RequestContext requestContext,  Type controllerType);
}

//用来获取Controller对象的
public interface IDependencyResolver
{
     object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}

//此类是用来封装管理IDependencyResolver类的实现类的。
public class DependencyResolver
{
     private static DependencyResolver _instance;
    public void InnerSetResolver(object commonServiceLocator);
    public void InnerSetResolver(IDependencyResolver resolver);
     public void InnerSetResolver(Func<Type, object> getService, Func<Type, IEnumerable<object>> getServices);
     public static void SetResolver(object commonServiceLocator);
    public static void SetResolver(IDependencyResolver resolver);
     public static void SetResolver(Func<Type, object> getService, Func<Type, IEnumerable<object>> getServices);
    public static IDependencyResolver Current { get; }
     public IDependencyResolver InnerCurrent { get; }
}
类关系图(图片引用自蒋金楠老师的博客):



总结:实例化DefaultControllerFactory类,如果IControllerActivator参数等于null或者没有传入参数,则DefaultControllerFactory类就会创建一个内部私有IControllerActivator接口实现类(DefaultControllerActivator)的实例

用来激活Controller类,而DefaultControllerActivator类会先判断内部私有委托resolverThunk是否为空,如果为空就返回DependencyResolver.Current静态属性下的IDependencyResolver实现类的实例,用来真正的创建激活

Controller类;如果不为空,就执行这个委托获得IDependencyResolver实现类的实例来激活Controller。(MVC默认是通过反射来激活Controller的)

Asp.net MVC的Controller激活理解,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。