Pregunta

Specifically, if I use NInject to create a bunch of objects that have been bound in singleton scope, I expect NInject to release them in reverse order.

I have a test case as follows, I want to know if I am doing something wrong, or if NInject2 has a bug.

I expect to see that, given that I have created an instance of Foo, and then an instance of Bar, NInject should be releasing Bar before it releases Foo! Why isn't it doing this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;

namespace ConsoleApplication1
{
    interface IFoo
    {
    }

    interface IBar
    {
    }

    class Foo : IFoo, IDisposable
    {
        public Foo()
        {
            System.Console.WriteLine("Created Foo Instance");
        }
        public void Dispose()
        {
            System.Console.WriteLine("Disposed Foo Instance");
        }
    }

    class Bar : IBar, IDisposable
    {
        public Bar(IFoo foo)
        {
            System.Console.WriteLine("Created Bar Instance");
        }
        public void Dispose()
        {
            System.Console.WriteLine("Disposed Bar Instance");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var kernel = new Ninject.StandardKernel())
            {
                kernel.Bind<IBar>().To<Bar>().InSingletonScope();
                kernel.Bind<IFoo>().To<Foo>().InSingletonScope();

                kernel.Get<IFoo>();
                kernel.Get<IBar>();
            }
        }
    }
}

Actual output:

Created Foo Instance
Created Bar Instance
Disposed Foo Instance
Disposed Bar Instance

Expected output:

Created Foo Instance
Created Bar Instance
Disposed Bar Instance
Disposed Foo Instance
¿Fue útil?

Solución

Ninject doesn't have reference counting at the moment. Therefore the instances are disposed in any order. If you want this you would have to write a ICache implementation which has reference counting.

Alternatively you can use define that Foo is in the scope of Bar using named scope. This will ensure that Foo won't be disposed before Bar.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top