17

How can I get the dependency resolver instance in web api? In asp.net mvc I can do DependencyResolver.Current, is there an equivalent in web api?

LordHits
  • 5,054
  • 3
  • 38
  • 51
ryudice
  • 36,476
  • 32
  • 115
  • 163
  • 1
    You probably already know this, but I have to provide the obligatory warning: You should be allowing the dependency resolver to inject the necessary dependencies into your classes, using the Api Controller as your context root, rather than going in search of the dependency resolver. – StriplingWarrior May 19 '14 at 23:07
  • 6
    yeah, the reason I need to use the resolver is inside a custom model binder, which will be set using the modelbinder attribute, instead of a model binder provider, so it will be instantiated with a paramterless constructor, so I need to use service location to get the dependencies. – ryudice May 19 '14 at 23:10
  • Just a hint: http://stackoverflow.com/questions/21919753/. Please, take it as another view - why to avoid `IDependencyResolver`. ServiceLocator could/should be seen as antipattern http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx – Radim Köhler May 20 '14 at 05:26

2 Answers2

19

Ignore what people are saying about being an anti-pattern. You won't get full DI coverage, especially with these young technologies. For example, at the time of writing, NInject has no support for injecting into middlewares.

To answer your question, the dependency resolver for a request is available through HttpRequestMessage.GetDependencyScope(). You can also use HttpConfiguration.DependencyResolver however beware that this one is not properly scoped for the request being executed.

I would recommend checking the documentation for the specific IOC implementation.

MoonStom
  • 2,847
  • 1
  • 26
  • 21
3

When using Ninject in Web API, you can use GlobalConfiguration.Configuration. For instance for IUserService:

(IUserService)System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserService))

Hope this helps you.

Sarah
  • 31
  • 2
  • 4