0

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:

  1. To register Foo1 and Foo2 as constructors/newables, have them injected in a ControllerFactory which instantiates them with a common bar object.

  2. 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 ?

lorefnon
  • 12,875
  • 6
  • 61
  • 93

1 Answers1

2

What you are looking for is requests scope but it is not available yet. Request scope allows you to define singletons for the context of the current request.

For generic use cases would be difficult to implement but in the case of HTTP server, it could be emulated it. If you want each HTTP requests to treat all dependencies as singletons within the context of the requests.

You could create a Container clone for each HTTP request but it would be probably not very efficient. I would recommend waiting until it is officially supported so you will be able to do:

container.bind<IFoo>("IFoo").to(Foo).inRequestScope();
container.bind<IBar>("IBar").to(Bar).inRequestScope();

container.bind<Controller>("Controller").to(FooBarController)
         .whenTargetNamed("FooBar");
Remo H. Jansen
  • 23,172
  • 11
  • 70
  • 93