MvcHandler.ProcessRequestInit()方法:
1.1获取控制器的名称string requiredString = this.RequestContext.RouteData.GetRequiredString("controller");
1.2创建控制器类工厂 返回IControllerFactory类型 默认创建的工厂实例为DefaultControllerFactory
factory = this.ControllerBuilder.GetControllerFactory();(注册IoC容器后,控制器类工厂类将交由IoC容器创建)
1.3 IControllerFactory.CreateController()
实则调用:DefaultControllerFactory.CreateController()
controller = factory.CreateController(this.RequestContext, requiredString);
DefaultControllerFactory.CreateController()方法:
1.3.1获取控制器类的Type:
Type controllerType = this.GetControllerType(requestContext, controllerName);
return this.GetControllerInstance(requestContext, controllerType);
重要步骤:
DefaultControllerFactory.GetControllerInstance()方法:(自定义的控制类工厂类继承DefaultFactory后,将调用自定义控制器类的GetControllerInstance方法)
1.3.2 IControllerActivator.Create()
实则调用DefaultControllerActivator.Create()
return this.ControllerActivator.Create(requestContext, controllerType);
DefaultControllerActivator.Create()方法:
1.3.3 IDependencyResolver.GetService()
实则调用DefaultDependencyResolver.GetService()
controller = (IController) (this._resolverThunk().GetService(controllerType) ?? Activator.CreateInstance(controllerType));
重要步骤:
DefaultDependencyResolver.GetService()方法:
1.3.4 return Activator.CreateInstance(serviceType);
使用IoC容器实现对ASP.Net MVC控制器的依赖注入
以Unity为例:(PM> install-package unity.mvc3)
1. 实现IDependencyResolver接口,在Application_Start()中通过DependencyResolver.SetResolver()告知MVC,将部分类型实例解析工作交由IoC容器来处理;
2. 继承DefaultControllerFactory,重写GetControllerInstance方法,使用IoC容器实现对控制器类的创建