问题
I am using Ninject in a n-tier application consisting of services, repositories, all wired up with the UnitOfWork pattern and Ninject. Further, I have different jobs executing in separate threads referencing those services and repositories.
Every now and again, seems at random times, I get an exception which crashes my console application executing the jobs. The exception is:
Application: Playground.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
Stack:
at Ninject.Activation.Caching.GarbageCollectionCachePruner.PruneCacheIfGarbageCollectorHasRun(System.Object)
at System.Threading.ExecutionContext.runTryCode(System.Object)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading._TimerCallback.PerformTimerCallback(System.Object)
As far as I understand this has something to do with the new Cache-and-Collection management in Ninject. However, I have not specified any Scopes for any Ninject bindins.
EDIT: Code samples:
Here is some of the code used(I believe the critical part):
public class DefaultUnitOfWork<TObjectContext> : Provider<ObjectContext>, IUnitOfWork, IServiceUnitOfWork
where TObjectContext : ObjectContext, new()
{
public DefaultUnitOfWork(){
_kernel = new CustomKernel(new CommonRepositoryModule(), new ServiceModule(), (NinjectModule)kernel.Get<IAmApplicationSpecificModule>());
}
}
I did end up checking the source before some time for another issue that I had. Basically, previously there were multiple instances of the kernel
being created and not disposed so in order to ovewrite this behaviour and dispose of them I implemented IDisposable
and in the I called the Dispose(bool disposing)
method on the kernel.
public void Dispose()
{
if (_kernel != null) _kernel.Dispose(true);
}
I hope that those samples are handy.
EDIT 2
I found the issue and it was completely my fault. Because of some scoping and disposing issues that I had, I modified the code so I dispose in the above mentioned way Dispose(true). This was messing up the caching mechanisms of Ninject. I re-implemented most of the code and no problem. Thanks for the ideas, though.
来源:https://stackoverflow.com/questions/6817227/ninject-garbage-collection