Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News ASP.NET Web API And Dependency Injection

ASP.NET Web API And Dependency Injection

This item in japanese

ASP.NET Web API comes with a Dependency Resolver interface that lets you inject dependencies into your controller. However Mark Seemann suggests it is better to use the IHttpControllerActivator interface for this purpose, with a couple of examples.

What’s the problem with using the IDependencyResolver? Mark explains –

The problem is that in an (IDependencyResolver) implementation, all you're given is a Type instance and asked to return an object, but you're not informed about the context. You don't know how deep in a dependency graph you are, and if you're being asked to provide an instance of the same service multiple times, you don't know whether it's within the same HTTP request, or whether it's for multiple concurrent HTTP requests.

Mark suggests its better to replace the IHttpControllerActivator interface in the Service Container. IHttpControllerActivator provides the HttpRequestMessage object which can provide the context. He shows a couple of examples, one using a simple custom DI container and another using a more robust DI container, Castle Windsor.

Note that in either methods, the controllers are created per HTTP request and disposed after the request is handled, the difference is mainly about what information is available to the container when resolving the Type.

On a broader note, this is just one of the examples how extensible ASP.NET is

Rate this Article