问题
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.
回答1:
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.
回答2:
If very much depends on what your service is doing. Normally you would opt for a singleton if there is some shared state, and as such synchronization around that state can lead to bottle necks that will effect scalability. If there is no shared state then you could still go for a singleton, but you have to be careful that you don't introduce any shared state at some future point (or if you do that you effectively lock around it).
If you return a new instance of the service everytime then you don't have to worry about that, and it could lead to better scalabilty/flexability in future, although returning a new instance can also effect scalability if that instance holds scarce resouces (e.g. db connections).
So, I think the real answer is "it depends". If you look at how frameworks handle this its generally some inbetween solution, such as maintaining a pool of services (e.g. db connection pools) , or the "per-session" model of Wcf.
来源:https://stackoverflow.com/questions/7123201/why-should-i-not-make-my-services-singletons-ioc