I have the following implementation of IDependencyScope
:
public class NinjectScope : IDependencyScope
{
protected IResolutionRoot resolutionRoot;
public NinjectScope(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).ToList();
}
~NinjectScope()
{
this.Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
IDisposable disposable = (IDisposable)this.resolutionRoot;
if (disposing)
{
// Free managed resources
if (this.resolutionRoot != null)
{
disposable.Dispose();
this.resolutionRoot = null;
}
}
}
}
As you can see it has Dispose(bool disposing)
implemented.
I was experiencing the error Error loading Ninject component ICache
when I added a Ninject Factory into one of my WebAPI classes.
As per this answer/question I realised that I was using the same implementation, except it wasn't my kernel being disposed of, it was being caused by the implementation of the Dispose(bool disposing)
method.
When I removed the implementation, the dependencies in my WebAPI Controller stopped causing the error, so it seems that the implementation of the Dispose(bool disposing)
method was causing the problem.
What is the correct implementation of Dispose()
for this particular class?
By calling the following to create the item that I am calling dispose on:
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
I learned from this answer, that only the object that created a disposable resource should call dispose, so maybe there aren't any things within my class that need disposing of