Search code examples
c#.netdependency-injectionninjectninject-extensions

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.


Solution

  • 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.