自定义 Razor View 基类和依赖项注入
我有一个自定义的 razor 视图基类,它具有本地化相关服务的属性,该服务通过属性注入使用 Unity 进行注入。
如果我在视图中使用该属性,该属性就会得到正确解析。但是,如果我尝试在布局(母版页)中使用相同的属性,则该属性尚未设置。
有人可以解释一下在 Unity 尝试解析视图并注入依赖项之前视图是如何渲染和编译的吗?
我尝试使用约定 [ViewName.Title] 设置每个视图的标题,并进行本地化服务查找,这在视图上效果很好,但我不想在每个视图中重复它。我感觉将逻辑移至 _ViewStart.cshtml,但 ViewBag 或我的本地化服务在那里不可用。
基类:
public abstract class LocalizeBaseWebViewPage<TModel> : WebViewPage<TModel>
{
[Microsoft.Practices.Unity.Dependency]
public ILocalizationService LocalizationService { get; set; }
public virtual string Localize(string key)
{
return LocalizationService.GetResource(key);
}
}
这适用于 Index.cshtml
@{
ViewBag.Title = Localize("Title");
Layout = "~/Views/Shared/_Layout.cshtml";
}
但不适用于 _Layout.cshtml,因为未为服务设置对象引用。
@{
ViewBag.Title = Localize("Title");
}
I have a custom razor view base class that has a property for a localization dependent service which is injected with Unity via property injection.
If I make use of the property in a view the property is properly resolved. But if I try to make use of the same property in a Layout (master page) that property is not being set yet.
Can someone please explain how the views get rendered and compiled before Unity tries to resolve the view and inject the dependencies.
I am trying to set the title of each view by using a convention [ViewName.Title] and have the localization service lookup that, which works great on the View, but I don't want to repeat it in every View. I have a feeling to move the logic to _ViewStart.cshtml but ViewBag or my localization service is not available there.
Base class:
public abstract class LocalizeBaseWebViewPage<TModel> : WebViewPage<TModel>
{
[Microsoft.Practices.Unity.Dependency]
public ILocalizationService LocalizationService { get; set; }
public virtual string Localize(string key)
{
return LocalizationService.GetResource(key);
}
}
This works in Index.cshtml
@{
ViewBag.Title = Localize("Title");
Layout = "~/Views/Shared/_Layout.cshtml";
}
But not in _Layout.cshtml, because of object reference not set for the service.
@{
ViewBag.Title = Localize("Title");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据设计,依赖注入在 asp.net mvc 3 布局页面中不起作用(这意味着母版页 DI 中的 BaseView 也不起作用)。因此,您可以为布局页面通过
UnityContainer
解析您的LocalizationService
(因此您需要将容器存储在HttpApplication
中并访问 Container 以通过它解决依赖关系)。顺便说一句,ActionFilters 依赖项中的 BTW 也不起作用。
Dependency Injection does not work in asp.net mvc 3 layout pages by design (thats mean that for the BaseView in master page DI not work also). So you can for a layout pages resolve your
LocalizationService
throughUnityContainer
(so you need store your Container withinHttpApplication
and access Container to resolve dependency through it).BTW in ActionFilters Dependency does not work also..