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");
}
The Dependency Injection (DI) Design PatternThe Dependency Resolver in ASP.NET MVC can allow you to register your dependency logic somewhere else (e.g. a container or a bag of clubs). The advantages of using Dependency Injection pattern and Inversion of Control are the following: Reduces class coupling.
Dependency Injection is the design pattern that helps us to create an application which loosely coupled. This means that objects should only have those dependencies that are required to complete tasks.
Using dependency injection, we can pass an instance of class C to class B, and pass an instance of B to class A, instead of having these classes to construct the instances of B and C. In the example, below, class Runner has a dependency on the class Logger.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With