Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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");
}
like image 704
adriaanp Avatar asked Jun 02 '11 09:06

adriaanp


People also ask

Does MVC use dependency injection?

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.

What is dependency injection in .NET Core MVC?

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.

What is dependency injection C# with example?

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.


1 Answers

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..

like image 54
Andrew Orsich Avatar answered Oct 26 '22 06:10

Andrew Orsich