Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I not make my services singletons (ioc)?

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.

like image 735
jgauffin Avatar asked Aug 19 '11 14:08

jgauffin


People also ask

Why should we not use Singleton pattern?

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.

What are the disadvantages of Singleton pattern?

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.

Should Viewmodels be singletons?

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.

How can singleton be prevented?

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.


1 Answers

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.

like image 104
jgauffin Avatar answered Oct 26 '22 20:10

jgauffin