开发者

Custom Razor View Base class and dependency injection

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.P开发者_开发百科ractices.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");
}


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 through UnityContainer(so you need store your Container within HttpApplication and access Container to resolve dependency through it).

BTW in ActionFilters Dependency does not work also..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜