Error: “No parameterless constructor defined for this object” when using Dependency Injection

Thoughts from the team
By    | January 10, 2012 | Tips & Tricks,

There are several reasons you might see the error “No parameterless constructor defined for this object” but I often see it in conjunction with Dependency Injection.  My setup is .NET MVC with Ninject, but I imagine this is applicable to many other combinations.  I use constructor injection to pass services and repositories to my controllers.

The error is triggered when you request an instance of a service you have not wired up properly in your DI config.  It’s a classic case of the error message not actually telling you what the real problem is.  For example, I just added the new dependency on IDirectDebitProvider to my BillingController:

public BillingController(IOrganisationRepository org, IDirectDebitProvider dd)
{
    // implementation
}

However, I had not added the following line to my Ninject configuration:

kernel.Bind<IDirectDebitProvider>().To<SmartDebit>();

For more, read our getting started guide for DI with ASP.NET MVC.

 

More like this