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

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?

主站蜘蛛池模板: 大渡口区| 乃东县| 永泰县| 铜陵市| 九寨沟县| 上蔡县| 华安县| 边坝县| 和龙市| 庐江县| 石景山区| 舞钢市| 香格里拉县| 全南县| 天等县| 肃南| 赤城县| 清水河县| 怀仁县| 科技| 泽库县| 威远县| 陆丰市| 高邮市| 隆尧县| 宁南县| 肇州县| 闻喜县| 泸西县| 长泰县| 启东市| 浑源县| 宝坻区| 北票市| 连云港市| 高青县| 方正县| 寻甸| 和静县| 阿勒泰市| 南投市|