ASP.NET MVC 5 Ninject

Ninject InSingletonScope still creates new objects

  • Me: Kernel.Bind<IDataCache>().To<InMemoryDataCache>().InSingletonScope();
  • Ninject: Haha, nah. Here’s a new object bro.

I don’t know why exactly this happens, but for some reason I’ve seen it happen in more than one project. Binding an implementation to an interface in singleton scope just DOESN’T do that. Instead, with every injection, the constructor is called and we get a new object. For some reason, InSingletonScope is just not working sometimes.

I did find a workaround though. I don’t feel good about it, but it does do what it is supposed to.

Kernel.Bind<IDataCache>().ToConstant(new InMemoryDataCache()); 

It’s ugly, but at least it’s a singleton.

Problems? Questions? Did I save you some time? Let me know on Twitter @kerryritter.

Leave a Reply

Your email address will not be published. Required fields are marked *