BT

Your opinion matters! Please fill in the InfoQ Survey!

ASP.NET Web API And Dependency Injection

| by Roopesh Shenoy Follow 0 Followers on Oct 04, 2012. Estimated reading time: 1 minute |

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

Adoption Stage
Style

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

Login to InfoQ to interact with what matters most to you.


Recover your password...

Follow

Follow your favorite topics and editors

Quick overview of most important highlights in the industry and on the site.

Like

More signal, less noise

Build your own feed by choosing topics you want to read about and editors you want to hear from.

Notifications

Stay up-to-date

Set up your notifications and don't miss out on content that matters to you

BT