BT
x Your opinion matters! Please fill in the InfoQ Survey about your reading habits!

ASP.NET Web API And Dependency Injection

by Roopesh Shenoy on Oct 04, 2012 |

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

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT