官术网_书友最值得收藏!

Controller life cycle

After a controller's type is located, ASP.NET Core starts a process to instantiate it. The process is as follows:

  1. The default controller factory (IControllerFactory) is obtained from the dependency injection (DI) framework and its CreateController method is called.
  2. The controller factory uses the registered controller activator (IControllerActivator), also obtained from the DI, to obtain an instance to the controller (IControllerActivator.Create).
  3. The action method is located using the IActionSelector from the DI.
  4. 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.
  5. The action method is called by the IActionInvoker from the IActionInvokerProvider, also obtained from the DI.
  6. Any filter methods are called upon the controller, the action method's filter attributes, and the global filters.
  7. The controller factory releases the controller (IControllerFactory.ReleaseController).
  8. The controller activator releases the controller (IControllerActivator.Release).
  9. 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.

主站蜘蛛池模板: 同江市| 溧水县| 鲁甸县| 汉源县| 张家界市| 丹阳市| 台东县| 陵水| 保山市| 子长县| 南溪县| 德江县| 新昌县| 铜山县| 青岛市| 济阳县| 清河县| 平潭县| 荥阳市| 太和县| 平原县| 昂仁县| 嵊州市| 晋中市| 静安区| 临夏县| 维西| 湖北省| 徐汇区| 白玉县| 肇东市| 许昌市| 荆门市| 彭水| 磴口县| 淄博市| 沐川县| 新晃| 乌兰浩特市| 丰顺县| 南平市|