There is a ton of great material on the Internet about dependency injection in ASP.NET Web API. One thing that I have not seen anywhere though, is any information about how to inject dependencies into the action, instead of a controller (constructor injection).

Injecting your dependencies directly into an action, rather than in the controller is a very reasonable approach, as it helps you falling into an over-injecting trap, and perhaps resolving too much things, for no real reason.

Laying out the ground

Suppose we have the following controller and a service that we’d like to inject. The example is trivial, but the solution is going to be the same regardless of the complexity.

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

publicinterfaceIHelloService

{

stringSayHello();

}

publicclassHelloService:IHelloService

{

publicstringSayHello()

{

return"Hello";

}

}

publicclassRequestDto

{

publicstringText{get;set;}

}

publicclassValuesController:ApiController

{

publicstringPost(RequestDto input,IHelloService helloService)

{

returnhelloService.SayHello()+" "+input.Text;

}

}

Of course if we just try to use this controller now, we’ll inevitably suffer from a null reference, as there is nothing yet that instructs Web API what to do with the enigmatic IHelloService action parameter.

Building a custom HttpParameterBinding

Web API uses various implementations of HttpParameterBinding abstarct class to hydrate the action parameters with values and objects extracted from the incoming HTTP request. Out of the box, Web API uses a couple of implementations of the parameter binding, with the two main ones being ModelBindingParameterBinder or FormatterParameterBinder.

For simple and primitive types, or for those parameters that are decorated with ModelBinderAttribute, ModelBindingParameterBinder is used. In other cases (complex types), FormatterParameterBinder is used – to deserialize the body of the request into a relevant object that can be passed into the action.

The real problem of performing injection into actions in ASP.NET Web API is that something, somehow, would need to be plugged into the Web API pipeline, so that such an injected action argument:

is not treated as all of the other ones (so prevent FormatterParameterBinder from kicking in for it)

is correctly resolved from whatever IoC container you are using

Finally, our injected parameter has to be resolved from somewhere – in our case that would be the IoC container registered in your Web API application.

You can easily introudce your own HttpParameterBinding to fulfill both of these requirements. The code for our InjectParameterBinding is shown below.

HttpParameterBinding has an abstract method ExecuteBindingAsync which you will need to ipmlement. It gives you access to contextual information such as HttpActionContext which in turns allows you to find out what action is executing, which controller is in use, or reach into the HttpConfiguration.

The semantic information about the parameter in play is represented by HttpParameterDescriptor. This instance is always passed through the constructor and you can use it to make decisions whether your custom binding should kick in for this particular parameter or not. In our case we simply rely on the parameter name and paramater type.

So, assuming our paramater type will be an interface that needs resolving from IoC, we can reach into the DependencyResolver (representing an adapter to our IoC container) and do just that. Then you will have to set the resolved instance on the ActionArguments dictionary of the HttpActionContext. This is the moment where we inject our service, and instead of a null, it will then be available from within then action as concrete instance resolved from IoC.

Plugging in an HttpParameterBinding

Once we have the InjectParameterBinding in place, the next step is to plug it in, and instruct Web API pipeline to use it when handling the incoming HTTP requests. Typically you plug in Web API services by registering them against HttpConfiguration.

This is possible here too, and we’ll return to that in a second, but first let’s look at an alternative method, which is creating a custom ParameterBindingAttribute. If you used Web API for at least a little, you are surely already familiar with FromUriAttribute and FromBodyAttribute that you can use to annotate parameters. Well, they are actually ParameterBindingAttribute. The class is shown below.

So if we now go back to our original example, it would need to look like this:

C#

1

2

3

4

5

6

7

publicclassValuesController:ApiController

{

publicstringPost(RequestDto input,[Inject]IHelloService helloService)

{

returnhelloService.SayHello()+" "+input.Text;

}

}

This ensures that Web API will not try to bind IHelloService from body of the request or do any other crazy stuff, but will defer to our InjectParameterBinding, which will try to resolve this interface from the dependency resolver. Of course, you can inject more services (as additional parameters) if you wish.

Some might argue this is not very elegant – an alternative way would be to register the binding globally, against HttpConfiguration.ParameterBindingRules collection. It’s a list of precendce that Web API goes through when trying to select a parameter binding relevant to handle a given parameter – as soon as a parameter binding suitable for handling the parameter is found, it will be used and no further lookup is performed.

You can register a Func<HttpParameterDescriptor,HttpParameterBinding> there, at position 0 so that it’s used first. There, you can inspect the HttpParameterDescriptor similarly to how we did in our InjectAttribute. If we decide that a given parameter should be using InjectParameterBinding we return that, otherwise, we return null which forces Web API to keep checking other parameter binding rules (the out of the box ones).

C#

1

2

3

4

5

6

7

8

9

config.ParameterBindingRules.Insert(0,param=>

{

if(param.ParameterType.IsInterface)

{

returnnewInjectParameterBinding(param);

}

returnnull;

});

In this case we simply check if the parameter is an interface, we will try to resolve it from the IoC, using InjectParameterBinding. The controller code can now be modified – we can ditch the [Inject] annotation and things still work.

C#

1

2

3

4

5

6

7

publicclassValuesController:ApiController

{

publicstringPost(RequestDto input,IHelloService helloService)

{

returnhelloService.SayHello()+" "+input.Text;

}

}

You can even package the registration into an extension method to make it a tad cleaner:

I think a much better solution is use an IOC container like StructureMap that supports deferred initialization of dependencies.

Instead of having ctor(IHelloService service) you merely do ctor(Lazy serviceFactory) then it’s only instantiated the first time you invoke serviceFactory.Value.

The cost of instantiating object, does any of this matter? Probably not. But i do feel it’s more pure that you’re not instantiating IHelloService for a method that doesn’t need it.

http://www.strathweb.com/ Filip W

then inject Lazy into an action instead of ctor and it’s even better.

My point was, if you have 5 actions on a controller, and each requires a different dependency, having all 5 dependencies or, as a matter of fact, even lazy dependencies, in the constructor, is an overinjection regardless of how you spin it.

http://www.Marisic.Net/ dotnetchris

I don’t really feel that methods should have dependencies. A method is a contract that requires data to function. To accept entire services in a method just doesn’t seem right to me. If you have a class that accepts so many dependencies in the constructor that it’s starting to get stupid, the class itself like violates the SRP.

Either way, regardless of what you think, controllers are not like other classes, you do not model them the same way as anything else (i.e. regarding inheritance or generics). Controllers are there to be an entry point into your application and there is not much SRP in play imho.

Either way, it’s a pointless discussion – if you don’t like the solution, just don’t use it.

http://jflood.net Joseph Flood

Having five different dependencies might indicate you need to redesign your responsibilities though, this solution doesn’t solve that, just makes it less visible.

I still like this approach though, particularly for single action controllers – i.e. it removes boiler plate ctor code. Nice work.

http://www.strathweb.com/ Filip W

I don’t disagree, but let’s not get paranoid. Especially with attribute routing, it’s easy to designate single controller to handle a lot of URIs and I don’t think it’s necessarily bad. Controllers should be lean, and should only provide HTTP entry points into your application. And SRP is something different that merely exposing HTTP endpoints.

You should really use actionContext.Request.GetDependencyScope() to resolve your dependencies from the current lifetime scope. As you have it now, everything will be resolved from the root scope which is only appropriate for singleton dependencies.