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?

3
  • 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. Commented May 19, 2014 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. Commented May 19, 2014 at 23:10
  • Just a hint: stackoverflow.com/questions/21919753. Please, take it as another view - why to avoid IDependencyResolver. ServiceLocator could/should be seen as antipattern blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx Commented May 20, 2014 at 5:26

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.