BT

InfoQ Homepage News ASP.NET Web API And Dependency Injection

ASP.NET Web API And Dependency Injection

Bookmarks

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
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.

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

Community comments

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

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

BT

Is your profile up-to-date? Please take a moment to review and update.

Note: If updating/changing your email, a validation request will be sent

Company name:
Company role:
Company size:
Country/Zone:
State/Province/Region:
You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.