How to ensure that NInject2 arranges objects in the correct order?

In particular, if I use NInject to create a bunch of objects that have been linked in the Singleton scope, I expect NInject to release them in the reverse order.

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

I expect to see that, given that I created an instance of Foo and then an instance of Bar, NInject must release Bar before it releases Foo! Why doesn't he do that?

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 Result:

 Created Foo Instance Created Bar Instance Disposed Bar Instance Disposed Foo Instance 
+4
source share
1 answer

Ninject does not currently have reference counting. Therefore, instances are placed in any order. If you want this, you will have to write an implementation of ICache that has reference counting.

Alternatively, you can use the definition that Foo is in a panel area using a named area. This ensures that Foo will not be deleted in front of the bar.

+3
source

Source: https://habr.com/ru/post/1392616/


All Articles