Search code examples
asp.net-mvcdependency-injectionasp.net-mvc-5unity-container

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.


Solution

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