在上一篇文章中我们获取到包含Controller所在的命名空间等信息的ControllerType对象之后,这篇就开始讲创建Controller对象。在DefaultControllerFactory中获取到ControllerType之后,紧接着就是创建Controller对象。
Type controllerType = GetControllerType(requestContext, controllerName); IController controller = GetControllerInstance(requestContext, controllerType); |
GetControllerInstance方法的实现如下:
protected internal virtual IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, String.Format( CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_NoControllerFound, requestContext.HttpContext.Request.Path)); } if (!typeof(IController).IsAssignableFrom(controllerType)) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_TypeDoesNotSubclassControllerBase, controllerType), "controllerType"); } return ControllerActivator.Create(requestContext, controllerType); } |
我们可以看到红色的代码就是返回创建好了的Controller对象,Create方法是属于接口IControllerActivator:该接口具体定义如下:
public interface IControllerActivator { IController Create(RequestContext requestContext, Type controllerType); } |
类DefaultControllerActivator实现了该接口,Cretae方法具体实现如下:
private class DefaultControllerActivator : IControllerActivator { public IController Create(RequestContext requestContext, Type controllerType) { } |
红色的代码首先判断GetService方法返回的对象能否转换为IController对象,如果可以则直接返回Cotroller对象,如果不能则根据controllerType创建一个Controller对象返回。我们来看GetService方法的实现的是接口IDependencyResolver里面的方法,由类DelegateBasedDependencyResolver来实现,具体如下:
public object GetService(Type type) { try { return _getService.Invoke(type); } catch { return null; } } |
到了这里我们就明白了真正创建Controller对象的地方就在这里,这个方法涉及到的Invoke方法,我们不做详解。