When MVC moves to System. Web. Mvc. MvcHandler, our analysis becomes much simpler, because it can be dynamically tracked directly in the source code.
Public class MvcHandler: IHttpHandler, IRequiresSessionState
{
Protected internal virtual void ProcessRequest (HttpContextBase httpContext)
{
AddVersionHeader (httpContext );
// Get the controller type
String controllerName = RequestContext. RouteData. GetRequiredString ("controller ");
// Instantiate the controller and call Execute
IControllerFactory factory = ControllerBuilder. GetControllerFactory ();
IController controller = factory. CreateController (RequestContext, controllerName );
...
Try
{
Controller. Execute (RequestContext );
}
Finally
{
Factory. ReleaseController (controller );
}
}
}
AddVersionHeader is used to add an Http Header.
HTTP/1.1 200 OK
...
X-AspNetMvc-Version: 1.0
...
Extract the requested ControllerName from RequestContext. RouteData, and then use ControllerFactory to generate the Controller object instance.
Public class ControllerBuilder
{
Public ControllerBuilder ()
{
SetControllerFactory (new DefaultControllerFactory ()
{
ControllerBuilder = this
});
}
Public void SetControllerFactory (IControllerFactory controllerFactory)
{
_ FactoryThunk = () => controllerFactory;
}
Public IControllerFactory GetControllerFactory ()
{
IControllerFactory controllerFactoryInstance = _ factoryThunk ();
Return controllerFactoryInstance;
}
}
ControllerBuilder. GetControllerFactory () actually returns a defacontrocontrollerfactory instance.
Public class DefaultControllerFactory: IControllerFactory
{
Public virtual IController CreateController (RequestContext requestContext, string controllerName)
{
...
RequestContext = requestContext;
Type controllerType = GetControllerType (controllerName );
IController controller = GetControllerInstance (controllerType );
Return controller;
}
Protected internal virtual IController GetControllerInstance (Type controllerType)
{
...
Return (IController) Activator. CreateInstance (controllerType );
...
}
}
DefaultControllerFactory implements some internal cache (ControllerTypeCache) processing to speed up subsequent access. However, the core code is very simple. Use ControllerName to obtain the ControllerType, and then reflect and create a Controller object instance. With this object instance, the following work is officially taken over by Controller. Execute.
Public class MvcHandler: IHttpHandler, IRequiresSessionState
{
Protected internal virtual void ProcessRequest (HttpContextBase httpContext)
{
...
IControllerFactory factory = ControllerBuilder. GetControllerFactory ();
IController controller = factory. CreateController (RequestContext, controllerName );
...
Try
{
Controller. Execute (RequestContext );
}
Finally
{
Factory. ReleaseController (controller );
}
}
}
- 2 pages in total:
- Previous Page
- 1
- 2
- Next Page