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?
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.
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? 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With