Why shouldn't I make my services solitary (ioc)?

Important: note that I do not mean singletones, for example, the presence of a private constructor and a static instance variable (or as someone suggested a static class), but single numbers that return the same instance from the inversion of the control container during application life time.

Many containers use a shorter default life. Either a new instance for each dependency (or for each request), or an instance for each area (for example, an HTTP request).

I wonder why containers advertise short-lived objects rather than long-lived ones?

Please 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.

+6
source share
2 answers

Did some more research

Because it’s easier to process session related information when using a shorter lifespan. Mixing lifetimes can also complicate matters.

My best practices

+1
source

If a lot depends on what your service does. Usually you choose a singleton if there is some kind of general condition, and such synchronization around this state can lead to the appearance of bottle necks that will affect scalability. If there is no general state, you can still go to singleton, but you must be careful that at some point in time you do not enter any general state (or if you do this, you actually block it).

If you return a new instance of the service each time, then you do not need to worry about this, and this may lead to better scalability / flexibility in the future, although returning a new instance may also lead to scalability if this instance has a resouces deficit (for example, db- connections).

So, I think the real answer is "it depends." If you look at how the infrastructure handles this, it’s usually some kind of intermediate solution, such as maintaining a service pool (for example, db connection pools) or a “per session” Wcf model.

0
source

Source: https://habr.com/ru/post/895422/


All Articles