DEV Community

Discussion on: Why Singletons Are Bad?

Collapse
 
ryannerd profile image
Ryan Jentzsch

Singletons are great if you are using Dependency Injection. JavaScript sucks at DI, so yeah don't use them with JS. Other truly Object Oriented languages such as Java, C#, and even PHP can benefit from from singletons with DI because they are injected as needed. The default for most DI libraries to use singletons. There are times when you want to instantiate non-singletons in a DI situation. Singletons are not a wholesale always bad as many things it IT, it depends

Collapse
 
amrtaher1234 profile image
Amr Mohamed

The way I understand Dependency injection is that you have an injection pool ( map of classes that you would inject ) and the injector injects such classes from its pool whenever its needed. They are not singletons by nature they are normal classes that gets injected, I'm not certian if this is the case in C# because I normally don't use it.

There are lots of implementations of dependency injection but in most of them it allows you to inject an instance of a class more than once ( meaning there will be more than one instance not a single one ) this indicates that simple DI does not inject singletons. This is how for example Angular implements it