1
votes

First time I call my service everything works fine. After that I receive this error: "Error loading Ninject component ICache\r\nNo such component has been registered in the kernel's component container.

The controller I am calling has IKernel as a parameter in its constructor and my guess is that this is the problem.

How am i supposed to pass a kernel object into my service?

My controller constructor:

public MyController(IKernel diContainer)
    {
        _diContainer = diContainer;
    }

Part of my Global.asax file:

var kernel = NinjectWebApi.Kernel;

kernel.Bind<IMyController().To<MyController();

//Set the dependency resolver to use ninject
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

I am using Ninject 3.2.

For my other services where I am not passing in the Kernel to the service this approach works fine.

public class NinjectDependencyScope : IDependencyScope
{
    private IResolutionRoot _resolver;

    public NinjectDependencyScope(IResolutionRoot resolver)
    {
        _resolver = resolver;
    }

    public object GetService(Type serviceType)
    {
        if (_resolver == null)
        {
            throw new ObjectDisposedException("this", "This scope has been disposed.");
        }

        return _resolver.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        if (_resolver == null)
        {
            throw new ObjectDisposedException("this", "This scope has been disposed.");
        }

        return _resolver.GetAll(serviceType);
    }

    public void Dispose()
    {
        var disposable = _resolver as IDisposable;
        disposable?.Dispose();
        _resolver = null;
    }
}

public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
    private readonly IKernel _kernel;

    public NinjectDependencyResolver(IKernel kernel) : base(kernel)
    {
        _kernel = kernel;
    }

    public IDependencyScope BeginScope()
    {
        return new NinjectDependencyScope(_kernel.BeginBlock());
    }
}
1
Have you manually wrote NinjectDependencyResolver or used something ready?Igor Lizunov
I realize now that the NinjectDependencyResolver is not an out of the box object. This is something my collegue has made. The name made me think it was coming from ninject itself. This might be worth investigating.jimmy

1 Answers

4
votes

It seems you dispose container inside your NinjectDependenvyResolver Dispose method.