typescriptdependency-injectioninversifyjs

How do I tell a Dependency Injection container to share an instance?


I am learning DI with Typescript (I use the tsyringe package in the example).

How can I tell a DI container that I want:

In the below example tsyringe creates two Bar instances (one in Foo and one for FooBar).

it("injects one Bar instance", () => {

  @injectable()
  class Bar {
    constructor() {}
    x = 1;
  }

  @injectable()
  class Foo {
    constructor(public myBar: Bar) {}
  }

  @injectable()
  class FooBar {
    constructor(public bar: Bar, public foo: Foo) {}
  }

  const fooBar = container.resolve(FooBar);
  fooBar.bar.x = 2;
  expect(fooBar.foo.myBar).toBe(2); // throws error (is 1)
});

Solution

  • For tsyringe, one has to use the @scoped decorator:

      @scoped(Lifecycle.ResolutionScoped)
      class Bar {
        constructor() {}
      }