我有以下代码块用于在我的解决方案中配置 Ninject:
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public object GetService(Type serviceType)
{
if (resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return resolver.GetAll(serviceType);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
resolver = null;
}
}
我的观点是这里使用的一次性模式不是必需的..
IDependencyScope 是 IDisposable,但我应该只在构造 IDisposable 成员时清理它们,但构造函数中注入的解析器不属于我的类(创建),并且 IResolutionRoot 不派生自/实现 IDisposable...
我在这里吗?
(查看这篇关于 IDisposable 模式的文章以供参考)
(编辑): 这实际上是一个基类,由以下类使用,因此无法在此处删除 IDisposable 实现...
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}