能否在视图外部获取ViewContext?注入后为空的问题咨询
问题解答
不需要必须通过标签助手来获取ViewContext,你的问题出在ViewUtility的构造逻辑上。
问题原因
[ViewContext]属性的赋值是在类实例化(构造函数执行)之后完成的,你在构造函数里直接调用(this.HtmlHelper as IViewContextAware).Contextualize(this.ViewContext)时,ViewContext还没被注入,自然是空值。
修复方案
调整逻辑,把Contextualize的调用移到ViewContext可用之后,以下两种方案任选其一:
方案1:实现IViewContextAware接口
框架会自动调用该接口的方法传入ViewContext,是更规范的实现方式:
public sealed class ViewUtility : IViewUtility, IViewContextAware { private readonly IHtmlHelper _htmlHelper; public ViewUtility(IHtmlHelper htmlHelper) { _htmlHelper = htmlHelper; } public ViewContext ViewContext { get; private set; } public ViewDataDictionary ViewData => this.ViewContext.ViewData; public IHtmlHelper HtmlHelper => _htmlHelper; public void Contextualize(ViewContext viewContext) { ViewContext = viewContext; // 给IHtmlHelper关联当前ViewContext if (_htmlHelper is IViewContextAware htmlHelperAware) { htmlHelperAware.Contextualize(viewContext); } } }
方案2:通过ViewContext的setter触发逻辑
如果不想实现接口,可修改属性的setter方法,在ViewContext注入后执行关联操作:
public sealed class ViewUtility : IViewUtility { private readonly IHtmlHelper _htmlHelper; public ViewUtility(IHtmlHelper htmlHelper) { _htmlHelper = htmlHelper; } private ViewContext _viewContext; [ViewContext] public ViewContext ViewContext { get => _viewContext; set { _viewContext = value; // 当ViewContext被注入后,给IHtmlHelper关联上下文 if (_htmlHelper is IViewContextAware htmlHelperAware) { htmlHelperAware.Contextualize(value); } } } public ViewDataDictionary ViewData => this.ViewContext.ViewData; public IHtmlHelper HtmlHelper => _htmlHelper; }
补充说明
- 视图外部的类(比如自定义工具类、服务)只要能被视图正确注入,通过
IViewContextAware接口或[ViewContext]属性就能获取ViewContext,无需依赖标签助手。 - 确保
IViewUtility已在DI容器中注册(例如在Program.cs中添加services.AddScoped<IViewUtility, ViewUtility>()),否则视图注入会失败。
内容的提问来源于stack exchange,提问作者SteinTech
相关产品推荐
相关产品推荐

