How to get instance of dependency resolver in ASP.NET web API

12,614

Solution 1

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.

Solution 2

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.

Share:
12,614
ryudice
Author by

ryudice

Updated on June 05, 2022

Comments

  • ryudice
    ryudice almost 2 years

    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?