- 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.
推薦閱讀
- 數(shù)據(jù)庫程序員面試筆試真題與解析
- Apache ZooKeeper Essentials
- R語言數(shù)據(jù)分析從入門到精通
- Android開發(fā)精要
- Microsoft Dynamics 365 Extensions Cookbook
- Linux核心技術(shù)從小白到大牛
- Python進(jìn)階編程:編寫更高效、優(yōu)雅的Python代碼
- Java程序設(shè)計(jì)與實(shí)踐教程(第2版)
- JavaScript從入門到精通(第3版)
- HTML5 and CSS3 Transition,Transformation,and Animation
- Oracle JDeveloper 11gR2 Cookbook
- Learning Python Design Patterns
- C語言程序設(shè)計(jì)
- Python機(jī)器學(xué)習(xí):預(yù)測分析核心算法
- Microsoft Dynamics AX 2012 R3 Financial Management