Reputation: 10838
I am learning ASP.NET MVC and I created a custom controller factory just for understanding the flow the application.
Below is the code of my custom controller factory.
My question is though the action of the controller is not called within this the action does get executed. How and where does it happen?
How does the Index action get executed when I don't call it from the factory?
using System.Web.Routing;
using System.Web.SessionState;
public class CustomControllerFactory : IControllerFactory
{
public IController CreateController(
RequestContext requestContext,
string controllerName)
{
Type targetType = null;
switch (controllerName)
{
case "first":
case "home":
targetType = typeof(FirstController);
break;
case "second":
targetType = typeof(SecondController);
break;
}
var typ = targetType.GetType();
return Activator.CreateInstance(targetType) as IController;
}
public SessionStateBehavior GetControllerSessionBehavior(
RequestContext requestContext,
string controllerName)
{
return System.Web.SessionState.SessionStateBehavior.Default;
}
public void ReleaseController(IController controller)
{
IDisposable dispose = controller as IDisposable;
if(dispose!= null)
dispose.Dispose();
}
}
And my FirstController
code as below:
public class FirstController : Controller
{
//
// GET: /First/
public ActionResult Index()
{
return Content("first cotnroller");
}
}
Upvotes: 0
Views: 375
Reputation: 6144
The ControllerFactory
is only responsible for creating an instance of the controller in question, and it is usually the place to implement a DI variation to instantiate controllers.
Executing the action is the next step in the request execution flow. It is done by the ControllerActionInvoker
via the InvokeAction
method,
public virtual bool InvokeAction(
ControllerContext controllerContext,
string actionName
)
which as shown, is being supplied with the controllerContext
that provides an instance of the controller class (i.e. FirstController
), and the name of the action to be executed, in this case "Index"
.
If you wish to also implement a custom version of the ActionInvoker
you can do so by implementing the IActionInvoker
interface, and setting the ActionInvoker
property for each controller to an instance of the CustomActionInvoker
.
this.ActionInvoker = new CustomActionInvoker();
in the controller's constructor (perhaps in a BaseController
constructor that all others controllers inherit from).
For the entire execution flow of a ASP.NET MVC application, refer to this answer.
Upvotes: 3