In Inversify, what is the best approach to have a single object instance (with transient life) shared between multiple objects.
So let us say we have:
@injectable()
class Foo1 {
@inject("bar")
private bar: IBar;
}
@injectable()
class Foo2 {
@inject("bar")
private bar: IBar;
}
@injectable()
class Controller {
@inject("foo1")
private foo1: Foo1;
@inject("foo2")
private foo2: Foo2;
}
Without making "bar" a singleton, is it possible to configure the IoC container such that both of the injected instances foo1
and foo2
get the same bar instance when Controller is injected somewhere.
The obvious approaches I can think of are:
To register Foo1 and Foo2 as constructors/newables, have them injected in a
ControllerFactory
which instantiates them with a common bar object.Use hierarchical DI and register bar as a singleton in the child container which is created everytime a new controller needs to be instantiated.
I don't think 1 is ideal because of the need for explicit instantiation.
Is there a better approach to handle this ?