computrius
computrius

Reputation: 702

Where is a singleton instance stored in ninject?

The title has it all. When I do this:

var kernel = new StandardKernel();
kernel.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass = kernel.Get<IMyClass>();

Where is the instance of MyClass stored? Is it stored in a static dictionary somewhere globally? Or is it stored in the kernel instance?

For example if I do this:

var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();

Will myClass1 be the same instance as myClass2 or will they be different instances.

To kind of jump on an inevitable question "Why do you need to do that?": It doesn't matter. That is not the point of the question. I have my reasons and just want to know how this piece works.

Upvotes: 0

Views: 445

Answers (2)

computrius
computrius

Reputation: 702

For others that are wondering: It stores it outside of the kernel. You will get the same instance with both kernels.

Edit - Test I ran to come to this conclusion:

var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();
var same = myClass1 == myClass2;
Console.WriteLine(same ? "Same" : "Different");

Output: Same

Edit Again: I must have had a typo because I tested again and got "Different".

Upvotes: -2

Jan Muncinsky
Jan Muncinsky

Reputation: 4408

So Ninject stores them here:

  /// <summary>Tracks instances for re-use in certain scopes.</summary>
  public class Cache : NinjectComponent, ICache, INinjectComponent, IDisposable, IPruneable
  {
    /// <summary>
    /// Contains all cached instances.
    /// This is a dictionary of scopes to a multimap for bindings to cache entries.
    /// </summary>
    private readonly IDictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>> entries = (IDictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>>) new Dictionary<object, Multimap<IBindingConfiguration, Cache.CacheEntry>>((IEqualityComparer<object>) new WeakReferenceEqualityComparer());
...

and Cache is scoped to instance of a kernel.

Will myClass1 be the same instance as myClass2 or will they be different instances.

Different. Cache is not static.

Upvotes: 2

Related Questions