"Error loading Ninject component ICache" 第二次调用我的服务

"Error loading Ninject component ICache" second time I call my service

我第一次调用我的服务时一切正常。之后我收到此错误: “加载 Ninject 组件时出错 ICache\r\nNo 该组件已在内核的组件容器中注册。

我正在调用的控制器在其构造函数中将 IKernel 作为参数,我猜这就是问题所在。

我应该如何将内核对象传递到我的服务中?

我的控制器构造函数:

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

我的 Global.asax 文件的一部分:

var kernel = NinjectWebApi.Kernel;

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

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

我正在使用 Ninject 3.2。

对于我没有将内核传递给服务的其他服务,这种方法工作正常。

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

您似乎在 NinjectDependenvyResolver Dispose 方法中处理了容器。