Reputation: 10725
Can someone please tell me the difference between a C# Singleton Class and a Ninject Singleton?
My current boss would like to convert a Singleton class into a Ninject Singleton.
This goes against methodology for me that I would have Ninject define the singleton rather than the class itself define the singleton. While we use Ninject throughout the project, it makes sense to use Ninject where needed. BUT it firmly makes sense to me that class should define the Singleton and not Ninject.
Thanks in advance!
Upvotes: 0
Views: 172
Reputation: 172606
There is a big difference between the Singleton design pattern and the Singleton Lifestyle that containers have. Registering something as 'singleton' in Ninject just means telling Ninject to only create a single instance for you.
The Ninject documentation explains quite well why the Singleton design pattern is a bad idea.
The problem with this is you basically have to lock down your type. Doing things this way will make your code end up rigid and inflexible. In particular, it'll be very difficult to unit test code that's implemented this way
The problem with the Singleton pattern is that you violate the Dependency Inversion Principle making your code dependent on an implementation. A singleton is basically an ambient context, and ambient contexts should in most cases be prevented.
Upvotes: 0
Reputation: 245389
There's a distinct difference between the two concepts that you're talking about.
A Singleton class means that only one instance of a class exists at any given time.
A Ninject Singleton simply means that Ninject will only ever inject a single instance of a class into your application. There's nothing to stop somebody from manually creating their own instance.
If you truly need a Singleton, don't rely on Ninject to do it for you. But if you only what your DI framework to use a single instance of a class for all of its injection, use Ninject.
Upvotes: 1