user1751825
user1751825

Reputation: 4309

Inject Service into MVC View with Unity.Mvc5

I've just started working with Unity Dependency Injection. I've figured out how to use it with Controllers, and with Models. However I'm not sure how to use it with Views...

What I want to do, is be able to retrieve lookup lists from within the View using a registered Service.

Looking at this URL http://blog.simontimms.com/2015/06/09/getting-lookup-data-into-you-view/ it shows how to do it with MVC6. It uses the @inject directive in the view. However I'm stuck with MVC5, which doesn't appear to have this directive.

Is there some MVC5 alternative to @inject?

I'm registering my services and repositories like so...

Public Shared Sub RegisterComponents()
    Dim container = New UnityContainer()

    container.RegisterType(Of IMyService, MyService)()
    container.RegisterType(Of IRepository(Of MyModel), MyRepository)()

    DependencyResolver.SetResolver(New UnityDependencyResolver(container))
End Sub

I access the services in my controllers like this...

<Dependency>
Public Property MyModelService() As IMyService

All I need to know now is how to inject the services into my razor views.

Upvotes: 2

Views: 1486

Answers (2)

hawkeyecoder
hawkeyecoder

Reputation: 571

This should probably have limited usage, but I have run into spots where it is handy.

C# Version using Unity

public class InjectedWebViewPage : InjectedWebViewPage<object>
{
}

public class InjectedWebViewPage<T> : WebViewPage<T>
{
    [Dependency] protected ISomeService SomeService { get; set; }
    /*
     * Other Services here...
     */

    public override void Execute()
    {
    }
}

Put the new class anywhere, just reference it in the Views/web.config as @user1751825 states

<pages pageBaseType="MyNamespace.InjectedWebViewPage"/>

Upvotes: 2

user1751825
user1751825

Reputation: 4309

I've found a relatively neat solution.

I just create my own view base class to inherit from WebViewPage (generic, and non-generic), and then put the injected service properties in there.

Namespace MyNamespace
    Public MustInherit Class MyWebViewPage
        Inherits MyWebViewPage(Of Object)

    End Class

    Public MustInherit Class MyWebViewPage(Of T)
        Inherits System.Web.Mvc.WebViewPage(Of T)

        <Dependency>
        Public Property MyModelService() As MyNamespace.IMyModelService

    End Class

End Namespace

I then add this to the Views/Web.config, like so...

<pages pageBaseType="MyNamespace.MyWebViewPage"/>

All of the service properties and methods are then automatically available to all my views.

Upvotes: 3

Related Questions