回到MvcHandler的 ProcessRequest , DefaultControllerFactory.CreateController(RequestContext, requiredString) 來返回 IController 實例。下面看看 DefaultControllerFactory的代碼:
通過反射來創建 Controller 實例 ,GetControllerType 裡面做了些緩存處理,以此來避免頻繁使用反射造成的性 能問題。繼續
MvcHandler.ProcessRequest(),在得到控制器實例後, MvcHandler 開始了調用 Controller.Execute() 來進一步後續操作,同時對其上 下文進一步封裝,除了前面創建的 RequestContext,還加上了當前這個 Controller 對象的引用,類名叫ControllerContext。
namespace System.Web.Mvc {
using System.Web.Routing;
[AspNetHostingPermission (System.Security.Permissions.SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission (System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class ControllerContext : RequestContext {
public ControllerContext(HttpContextBase httpContext, RouteData routeData, IController controller)
: base(httpContext, routeData) {
if (controller == null) {
throw new ArgumentNullException("controller");
}
Controller = controller;
}
public ControllerContext(RequestContext requestContext, IController controller)
: this(GetRequestContext (requestContext).HttpContext, GetRequestContext (requestContext).RouteData, controller) {
}
public IController Controller {
get;
private set;
}
internal static RequestContext GetRequestContext(RequestContext requestContext) {
if (requestContext == null) {
throw new ArgumentNullException("requestContext");
}
return requestContext;
}
}
}