Custom Razor View Base Class and Dependency Injection

I have my own razor view view class that has a property for the localization-dependent service that Unity introduces by pasting properties.

If I use a property in a view, the property is correctly resolved. But if I try to use the same property in the layout (main page), this property has not yet been set.

Can someone explain how views are processed and compiled before Unity tries to resolve the view and introduce dependencies.

I am trying to set the title of each view using the [ViewName.Title] convention and find a localization search that works fine in the view, but I don't want to repeat it in every view. I had a desire to move the logic to _ViewStart.cshtml, but the ViewBag or my localization service are 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 the object reference is not set for the service.

 @{ ViewBag.Title = Localize("Title"); } 
+7
source share
1 answer

Injection Dependency does not work in asp.net mvc 3 page layouts by design (this means that for BaseView on the main page DI does not work either). Thus, you can UnityContainer LocalizationService for the layout pages through the UnityContainer (so you need to store the Container inside HttpApplication and access the Container to allow it through it).

BTW in ActionFilters Dependency also doesn't work.

+2
source

All Articles