1

It's probably a duplicate, but no somution have worked for me; so I post the question one more time.

I have a web project using both MVC5 and WebApi2. I've put constructor DI with Ninject on those controllers, but when I try to reach a web api controller I have this exception :

Make sure that the controller has a parameterless public constructor.

I have this in my NinjectWebCommon.CreateKernel() method :

var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

RegisterServices(kernel);

GlobalConfiguration.Configuration.DependencyResolver = new Ninject.Web.WebApi.NinjectDependencyResolver(kernel);
System.Web.Mvc.DependencyResolver.SetResolver(new Ninject.Web.Mvc.NinjectDependencyResolver(kernel));

return kernel;

Here is the controller relevant content :

private MyDependency dependency;

public MyController(MyDependency injectedDependency)
{
    this.dependency = injectedDependency;
}

And the relevant binding :

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<MyDependency>().ToSelf().InSingletonScope();
}

I tried creating a custom resolver, following this solution, but I still have the exception. I also tried using Unity, and I have the same problem.

What else can I try ?

Community
  • 1
  • 1
gobes
  • 507
  • 7
  • 25
  • does `MyDependency` have any dependencies itself? If so then they will also have to be registered. – Nkosi Mar 24 '17 at 14:35
  • Holy sh*t, @Nkosi, you are right ! `MyDependency` have 4 dependencies itself, and ONE was not registered. I was sure to have checked all of them... it would be great if Ninject give some information about forgotten binding... Anyway, post your comment as an answer, I'll accept it. – gobes Mar 24 '17 at 15:27

1 Answers1

1

If MyDependency has any dependencies itself then those dependencies will also have to be registered with the kernel, otherwise it will result in an exception when trying to resolve the MyDependency during constructor injection of the controller.

Nkosi
  • 235,767
  • 35
  • 427
  • 472