"加载Ninject组件ICache"时出错我第二次打电话给我的服务

时间:2016-12-12 08:19:30

标签: dependency-injection ninject ninject.web.mvc

我第一次打电话给我的服务一切正常。之后我收到此错误: "加载Ninject组件ICache \ r \ n时出错\ n此类组件已在内核的组件容器中注册。

我正在调用的控制器在其构造函数中将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());
    }
}

1 个答案:

答案 0 :(得分:2)

您似乎在NinjectDependenvyResolver Dispose方法中部署了容器。