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 ?

2
  • does MyDependency have any dependencies itself? If so then they will also have to be registered. Commented Mar 24, 2017 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. Commented Mar 24, 2017 at 15:27

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.