Disposing of out-of-scoped objects in Ninject kernel

239 Views Asked by At

I'm trying to figure out how the kernel disposed of objects it has in it. For example, the following code creates two scopes and asserts that the same object is resolves when the scope if the same, a different one when it's different.

[Test]
public void DisposingScope()
{

    var kernel = new StandardKernel();

    ScopeObject scopeObject = null;

    kernel.Bind<IBall>().To<RedBall>().InScope(context => scopeObject);

    var scope1 = new ScopeObject();
    var scope2 = new ScopeObject();

    scopeObject = scope1;

    var ball1A = kernel.Get<IBall>();
    var ball1B = kernel.Get<IBall>();

    Assert.That(ball1A, Is.SameAs(ball1B));  // <== Balls from the same scope

    scopeObject = scope2;
    var ball2 = kernel.Get<IBall>();
    Assert.That(ball2, Is.Not.SameAs(ball1A));  // <== Balls from different scopes
}

As I have two scopes, there are two instances of RedBall held in the container.

  • How\when do these get removed?
  • How can I extend my test to prove that the balls in the container are disposed?
1

There are 1 best solutions below

0
On

Ninject retains a WeakReference to the scope. If ninject is not being (actively - INotifyWhenDisposed) informed about the scope ending, it will check periodically whether the scope is still alive. If it's dead, it will dispose of the scoped resources belonging to that scope.

Testing that disposal works correctly can be done by mocking the IDisposable and verifying that Dispose() was called when expected. Testing garbage collection can be done by using JetBrains' dotMemory Unit.

For more information see my extensive answer to this question. The question also shows an example of how to use dotMemory Unit.