Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 988
ryudice Avatar asked May 19 '14 23:05

ryudice


People also ask

What is the web API dependency resolver?

But now there is a problem, because your application doesn't create the controller directly. Web API creates the controller when it routes the request, and Web API doesn't know anything about IProductRepository. This is where the Web API dependency resolver comes in. Web API defines the IDependencyResolver interface for resolving dependencies.

What is the scope of httpconfiguration dependency resolver?

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope. Web API then calls GetService on the child scope to create the controller.

What is dependency injection in web API?

What is Dependency Injection? This tutorial shows how to inject dependencies into your ASP.NET Web API controller. What is Dependency Injection? A dependency is any object that another object requires.

How do I get rid of dependencies in web API?

Web API then calls GetService on the child scope to create the controller. When request is complete, Web API calls Dispose on the child scope. Use the Dispose method to dispose of the controller's dependencies.


2 Answers

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.

like image 118
MoonStom Avatar answered Oct 22 '22 23:10

MoonStom


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.

like image 41
Sarah Avatar answered Oct 23 '22 00:10

Sarah