Ninject binding to IKernel fails in ApiController with error "Error loading Ninject component ICache"

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!

Answers


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;
    }
}

Need Your Help

Teradata SQL Same Day Prior Year in same Week

sql teradata

Need help figuring out how to determine if the date is the same 'day' as today in teradata. IE, today 12/1/15 Tuesday, same day last year was actually 12/2/2014 Tuesday.

Getting pixel data from CGImageRef contains extra bytes?

ios bitmap core-graphics cgimage

I'm looking at optimizing a routine that fetches the pixel data from a CGImage. The way this currently is done (very inefficiently) is to create a new CGContext, draw the CGImage into the context, ...