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

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.

主站蜘蛛池模板: 华容县| 铜鼓县| 广水市| 西畴县| 吴川市| 禄丰县| 石台县| 焉耆| 卓资县| 中方县| 武宁县| 尉犁县| 逊克县| 佛冈县| 文成县| 沙坪坝区| 苏尼特左旗| 昔阳县| 花垣县| 格尔木市| 灵宝市| 武威市| 长春市| 漯河市| 太康县| 绿春县| 枞阳县| 永和县| 化隆| 鹿泉市| 黄大仙区| 花莲县| 高尔夫| 澳门| 额尔古纳市| 黄梅县| 陕西省| 上蔡县| 安丘市| 黑河市| 宾阳县|