How to create object from factory and have it to be a singleton as well?
kunxin-chor opened this issue · comments
I have a complex object which I am creating through a factory, and I need it to be injected as a singleton too. Can do I via adic, or do I need to create the object as a singleton the usual way?
Hello @kunxin-chor!
Factories only return the objects they create, without storing them in the container by default.
You could receive the container on the factory (e.g. by constructor) and, just before returning the object, bind it as a singleton (however, before recreating it, always check if the object is already bound to the container to prevent two singletons!).
Take a look at the CubeFactory
class on the example 07 - Factory. It does almost everything you need.
Hope that helps!
The issue will be closed. Please reopen it if you have any other questions regarding the subject!