1

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;
    }
}
1
  • Sorry, but "which would be the easiest to configure" is primary opinion based. Besides, Autofac, Castle, Ninject, StructureMap, Simple Injector, Unity all have integration packages for Web API. Commented Mar 25, 2014 at 12:52

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.