title: Dependency injection for ASP.NET Web API action method parameters
body: <p>I am working on an ASP.NET Web API project in C# for a JSON interface to a mobile application. My idea was to create interfaces for all requests and then only use these interfaces in the Web API code.</p>
  
  <p>I ended up with something like this:</p>
  
  <pre><code>public interface IApiObject {}
  public interface IApiResponse&lt;T&gt; : IApiObject where T : IApiObject {}
  public interface IApiRegistrationRequest : IApiObject {}
  </code></pre>
  
  <p>My controller looks like this:</p>
  
  <pre><code>public class MyApiController : ApiController
  {
  
      public IApiResponse&lt;IApiObject&gt; Register(IApiRegistrationRequest request) {
          // do some stuff
      }
  }
  </code></pre>
  
  <p>My Web API project also contains implementations of these interfaces.</p>
  
  <p>I assumed Web API projects use model binding like MVC projects do, so I created an <a href="http://www.matthidinger.com/archive/2011/08/16/An-inheritance-aware-ModelBinderProvider-in-MVC-3.aspx" rel="noreferrer">inheritance aware ModelBinderProvider</a> for providing a binder for all IApiObjects and a custom model binder using a Unity container to resolve the interfaces to their implementations.</p>
  
  <p>However, after some more investigation, I came across <a href="http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx" rel="noreferrer">How Web API does parameter binding</a> and found out that Web API uses formatters instead of model binders for complex types. The linked blog post recommends using a ModelBinderAttribute on my action parameters, but that attribute only accepts a type as a parameter. My custom model binder does, however, not contain an empty constructor (it needs a unity container), so I would need to pass an instance of it.</p>
  
  <p>The other way I can think of is using dependency injection for the formatters. Unfortunately, I am unfamiliar with them as I have never used them before.</p>
  
  <p>Which is the right way to go? And how do I do it?</p>