Ninject InSingletonScope still creates new objects
💻 coding

Ninject InSingletonScope still creates new objects

1 min read 97 words
1 min read
ShareWhatsAppPost on X
  • 1Ninject's InSingletonScope sometimes fails to create a single instance, resulting in new objects on each injection.
  • 2This issue has been observed across multiple projects, indicating a potential flaw in Ninject's singleton implementation.
  • 3A workaround involves binding to a constant instance, which effectively creates a singleton despite being an unconventional solution.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Ninject's InSingletonScope sometimes fails to create a single instance, resulting in new objects on each injection."

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.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 21 March 2019 · 1 min read · 97 words

Part of AskGif Blog · coding

You might also like

Ninject InSingletonScope still creates new objects | AskGif Blog