• 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的)

  • 相关阅读:
    UnicodeDecodeError: 'gbk' codec can't decode byte 0xb0 in position 279: illegal multibyte sequence
    fish-redux快速创建文件夹模板 FishReduxTemplate
    一个很好的banner组件
    Class类的特性(上)
    兼容安卓和ios实现一键复制内容到剪切板
    React组件,React和生命周期
    vue数据双向绑定原理
    javascript的Object对象的defineProperty和defineProperties
    javascript 判断数据类型
    原生http模块与使用express框架对比
  • 原文地址:https://www.cnblogs.com/lxiang/p/3897293.html
Copyright © 2020-2023  润新知