Dependency Injection with ASP.NET Web API

I am trying to use DI in my ASP.NET Web API Controller. Apparently there are a few implementations out there. I was just wondering which of these (Castle, Ninject, unity etc.) would be the easiest to configure/maintain in combination with ASP.NET Web API? I am getting this error:

DI.Controllers.ImportJsonController’ does not have a default constructor.

If I add an empty constructor, then the constructor with IFilter is ignored.

This is my controller:

public class ImportJsonController : ApiController
{
    private readonly IFilter _filter;

    public ImportJsonController(IFilter filter)
    {
        _filter = filter;
    }

    public HttpResponseMessage Post([FromBody]dynamic value)
    {
        //do something
        return response;
    }
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You don’t need a DI Container for this. Here’s how to do it by hand:

public class PoorMansCompositionRoot : IHttpControllerActivator
{
    public IHttpController Create(
        HttpRequestMessage request,
        HttpControllerDescriptor controllerDescriptor,
        Type controllerType)
    {
        if (controllerType == typeof(ImportJsonController))
            return new ImportJsonController(new MyFilter());

        return null;
    }
}

You need to tell ASP.NET Web API about this class (e.g. in your Global.asax):

GlobalConfiguration.Configuration.Services.Replace(
    typeof(IHttpControllerActivator),
    new PoorMansCompositionRoot());

You can read about all the details here: http://blog.ploeh.dk/2012/09/28/DependencyInjectionandLifetimeManagementwithASP.NETWebAPI

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply