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

Understanding the view life cycle

When an action signals that a view should be rendered, the following occurs (in a simplified way):

  • The action returns a ViewResult object because ViewResult implements IActionResult, and its ExecuteResultAsync method is called asynchronously.
  • The default implementation attempts to find ViewResultExecutor from the dependency injection (DI) framework.
  • The FindView method is called on ViewResultExecutor, which uses an injected ICompositeViewEngine, also obtained from the DI framework, to obtain IView from the list of registered view engines.
  • The view engine chosen will be an implementation of IRazorViewEngine (which, in turn, extends IViewEngine).
  • The IView implementation uses the registered IFileProviders to load the view file.
  • ViewResultExecutor is then asked to invoke the view, through its ExecuteAsync method, which ends up invoking the ExecuteAsync methods of the base ViewExecutor.
  • ViewExecutor builds and initializes some infrastructure objects such as ViewContext and ends up invoking IView RenderAsync method.
  • Another service (ICompilationService) is used to compile the C# code.
  • The registered IRazorPageFactoryProvider creates a factory method for creating a .NET class that inherits from IRazorPage.
  • IRazorPageActivator is passed an instance of the new IRazorPage.
  • The ExecuteAsync method of IRazorPage is called.

Here, I didn't mention the filters, but they are here as well, except action filters, as I said.

Why is this important? Well, you may need to implement your own version of—say—IRazorPageActivator so that you can perform some custom initialization or DI in the Razor view, as illustrated in the following code block:

public class CustomRazorPageActivator : IRazorPageActivator
{
private readonly IRazorPageActivator _activator;

public CustomRazorPageActivator(
IModelMetadataProvider metadataProvider,
IUrlHelperFactory urlHelperFactory,
IJsonHelper jsonHelper,
DiagnosticSource diagnosticSource,
HtmlEncoder htmlEncoder,
IModelExpressionProvider modelExpressionProvider)
{
this._activator = new RazorPageActivator(
metadataProvider,
urlHelperFactory,
jsonHelper,
diagnosticSource, htmlEncoder,
modelExpressionProvider);
}

public void Activate(IRazorPage page, ViewContext context)
{
if (page is ICustomInitializable)
{
(page as ICustomInitializable).Init(context);
}

this._activator.Activate(page, context);
}
}

All you need to do is register this implementation in ConfigureServices, for the IRazorPageActivator service, like this:

services.AddSingleton<IRazorPageActivator, CustomRazorPageActivator>();

Now, how are views located?

主站蜘蛛池模板: 靖远县| 修武县| 兰坪| 隆回县| 金沙县| 五莲县| 长垣县| 四平市| 石家庄市| 宁海县| 台南县| 靖州| 苏尼特左旗| 宜城市| 大庆市| 阿克苏市| 莱芜市| 武鸣县| 临泽县| 宁乡县| 砀山县| 广东省| 盐津县| 水城县| 奉节县| 麟游县| 苏尼特左旗| 滦南县| 昌图县| 西林县| 安阳市| 海盐县| 嘉兴市| 蒙山县| 闸北区| 万州区| 汽车| 鄄城县| 西贡区| 鲁甸县| 行唐县|