- Modern Web Development with ASP.NET Core 3
- Ricardo Peres
- 298字
- 2021-06-18 18:36:01
Controller life cycle
After a controller's type is located, ASP.NET Core starts a process to instantiate it. The process is as follows:
- The default controller factory (IControllerFactory) is obtained from the dependency injection (DI) framework and its CreateController method is called.
- The controller factory uses the registered controller activator (IControllerActivator), also obtained from the DI, to obtain an instance to the controller (IControllerActivator.Create).
- The action method is located using the IActionSelector from the DI.
- If the controller implements any filter interfaces (IActionFilter, IResourceFilter, and more), or if the action has any filter attributes, then the appropriate methods are called upon it and on global filters.
- The action method is called by the IActionInvoker from the IActionInvokerProvider, also obtained from the DI.
- Any filter methods are called upon the controller, the action method's filter attributes, and the global filters.
- The controller factory releases the controller (IControllerFactory.ReleaseController).
- The controller activator releases the controller (IControllerActivator.Release).
- If the controller implements IDisposable, then the Dispose method is called upon it.
Most of these components can be registered through the built-in DI framework—for example, if you want to replace the default IControllerFactory implementation, then you could do this in the ConfigureServices method:
services.AddSingleton<IControllerFactory, CustomControllerFactory>();
Now, imagine that you wanted to write an action selector that would redirect all calls to a specific method of a class. You could write a redirect action selector as follows:
public class RedirectActionSelector : IActionSelector
{
publicActionDescriptor SelectBestCandidate(
RouteContext context,
IReadOnlyList<ActionDescriptor> candidates)
{
var descriptor = new ControllerActionDescriptor();
descriptor.ControllerName = typeof(MyController).Name;
descriptor.MethodInfo = typeof(MyController).
GetMethod("MyAction");
descriptor.ActionName = descriptor.MethodInfo.Name;
return descriptor;
}
public IReadOnlyList<ActionDescriptor> SelectCandidates(
RouteContext context)
{
return new List<ActionDescriptor>();
}
}
This will redirect any request to the MyAction method of the MyController class. Hey, it's just for fun, remember?
Now let's have a look at actions.