0
votes

I have the following simple ApiController example that is failing.

public class TestAPIController : ApiController
{
    public TestAPIController(IKernel kernel) { }

    [HttpGet]
    public string Test()
    {
        return "success! " + DateTimeOffset.Now.ToString("F");
    }
}

This gives me the error:

Error loading Ninject component ICache No such component has been registered in the kernel's component container.

I have the package Ninject.WebApi.DependencyResolver installed but it is still failing.

Here is my CreateKernel class in NinjectWebCommon:

private static IKernel CreateKernel()
    {        
        var kernel = new StandardKernel(new VBNinjectModule());
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);

        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        //GlobalConfiguration.Configuration.DependencyResolver = new VBNinjectDependencyResolver(kernel);
        GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
        return kernel;
    }

Using:

Ninject 3.0.1.10

Ninject.MVC3 3.0.0.6

Ninject.Web.Common: 3.0.0.7

Ninject.WebApi.DependencyResolver 0.1.4758.24814

Thanks in advance for the help.

Cheers!

1
I think ninject auto-binds IKernel (or was it IResolutionRoot?), you should not need to bind it. Injection of Func factory works automatically, you don't need to specify a .Bind<Func<IFoo>>() (as long as there is a binding for IFoo) anyway. Also try injecting IResolutionRoot. - BatteryBackupUnit

1 Answers

0
votes

You do not want to inject IKernel to a controller. Instead, you want to register your service, and inject that service to the controller.

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

    RegisterServices(kernel);

    GlobalConfiguration.Configuration.DependencyResolver = 
       new NinjectDependencyResolver(kernel);

    return kernel;
}

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IMyService>().To<MyService>().InRequestScope();
}      

// Your api controller
public class TestAPIController : ApiController
{
    private readonly IMyService _myService ;

    public TestAPIController(IMyService myService) 
    { 
        _myService = myService;
    }
}