Dependency injection directly into actions in ASP.NET Web API

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.

With Web API, it’s actually extremely easy to do, so let’s go ahead and implement it.

More after the jump.

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.

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.

It’s a way to tell Web API – for this parameter, use this specific binding. This is how it will look in our case:

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

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

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.

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

So now all you need to call is:

Registering Dependency Resolver

The last thing to do is to register any dependency resolver – my favorite IoC container is Autofac, so I’m going to use that, from their Autofac.WebApi2 Nuget package.

Below is the whole setup of a Web API Startup class, with Autofac, our sample HelloService and the parameter binding allowing us to do action injection.

And that’s it!

Be Sociable, Share!

  • ghidello


  • Nicolas Herrera

    awesome post! thanks for sharing

  • Pingback: Dependency injection directly into actions in A...()

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1663()

  • http://www.Marisic.Net/ dotnetchris

    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.

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

        • Filip W

          I think the DDD crowd would beg to differ ( :)

          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.

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

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

  • Pingback: Andrey on .NET | Интересности #43()

  • Michael Petito

    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.

    • Filip W

      ugh. good catch!

  • SB

    Hi Filip, is there a way to combine the DTO and the service? That is, intercept the creation of the service but then pass the object on so that it gets populated from the request?

  • David Karen

    Thanks for detailed article ! Quick question, How would you manage if I have to pass “input” to “HelloService” in constructor of HelloService? Or I have to create new method say “Populate()” within IHelloService and call that to initialize all params in constructor of HelloService. Thanks !