Important: Do note that I do not mean singletons as in having a private constructor and a static instance variable (or as someone suggested a static class), but singletons as returning the same instance from the inversion of control container during the application lifetime.
Many containers use a short life time per default. Either a new instance per dependency (or per request) or an instance per scope (such as a HTTP request).
I'm wondering why containers promote short lived objects instead of long lived?
Do note that I usually only register my services in the container. I register factories in the container if I need to create domain models etc.
By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.
Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.
No. There's no reason a ViewModel should be a Singleton. You actually WANT multiple instances (since each is going to vary) rather than a single instance that lives for the run of the application.
Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.
Did some more research.
Because it's easier to handle session specific information when using a shorter lifetime. Mixing lifetimes can also complicate things.
Every time you take a scoped dependency in a single instance service it will work fine at start. However, scoped services are typically not designed to be long lived. If they use a external resource like a socket connection or a database connection it will probably be lost at one point.
Since the scoped service is not design for that, it will probably start failing, and therefore the single instance service will also start failing and continue to do that until the application is restarted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With