Basic
Basic

Reputation: 26766

How to use my own dependency resolver in MVC4's APIController

Back in MVC3, I had a custom ControllerFactory which would use my own container (as abstracted by my business logic) to instantiate controllers and pass them services they needed.

I'm trying to implement something similar in MVC4 using the new ApiController.

I've got a static/shared method Core.DependencyResolverFactory.Resolver which returns an IDependencyResolver. This in turn has a number of Resolve(...) and ResolveAll(...) methods and overloads.

So... How can I implement the same thing in MVC4?

I've tried setting up my own ServiceLocator but can't find the interface Microsoft.Practices.ServiceLocation.IServiceLocator in any of the framework assemblies.

I'm not too worried about being tied to an underlying container as it's already being abstracted by the BL, so really I just need a quick and dirty way to inject my classes into MVC's DI.

Can someone please point me at a good tutorial?

What I've got at the moment....

Sub Application_Start()
    ...Snip...

    'Suggested in the link on jrummel's answer...
    GlobalConfiguration.Configuration.DependencyResolver = New WebResolver
    'It fails due to DependencyResolver not being defined


    'I do have a 
    GlobalConfiguration.Configuration.ServiceResolver = New WebResolver
    'but it's read-only and it is of type System.Web.Http.Services.DependencyResolver not IDependencyResolver

End Sub

Private Class WebResolver
    Implements IDependencyResolver

    Private Resolver As Common.Interfaces.IDependencyResolver = Core.DependencyResolverFactory.QuickResolver

    Public Function GetService(serviceType As Type) As Object Implements IDependencyResolver.GetService
        Return Resolver.Resolve(serviceType)
    End Function

    Public Function GetServices(serviceType As Type) As IEnumerable(Of Object) Implements IDependencyResolver.GetServices
        Return Resolver.ResolveAll(serviceType)
    End Function
End Class

Upvotes: 4

Views: 7895

Answers (1)

jrummell
jrummell

Reputation: 43087

ASP.NET Web API beta ships with its own IDependencyResolver, separate from MVC.

There's a tutorial on asp.net: Using the Web API Dependency Resolver

You can get ServiceLocator from NuGet.

Upvotes: 3

Related Questions