microsoft / tsyringe

Lightweight dependency injection container for JavaScript/TypeScript
MIT License
5.16k stars 173 forks source link

Error in delay() example from readme? #113

Closed Obiwarn closed 4 years ago

Obiwarn commented 4 years ago

In a Jest test it says: ReferenceError: Bar is not defined

it("injects a circular dep", () => {
  @injectable()
  class Foo {
    constructor(@inject(delay(() => Bar)) public bar: Bar) {}
  }

  @injectable()
  class Bar {
    constructor(@inject(delay(() => Foo)) public foo: Foo) {}
  }

  // construction of foo is possible
  const foo = container.resolve(Foo);
});
emilioastarita commented 4 years ago

You must create these classes in different files to be able to run in the context of a jest test. That's the reason why we wrote tests cases for delay helpers using fixtures/*.ts folder.

Probably running the example without jest will work:

import "reflect-metadata";
import {injectable, inject, container, delay} from "tsyringe";

@injectable()
class Foo {
    constructor(@inject(delay(() => Bar)) public bar: Bar) {}
}

@injectable()
class Bar {
    constructor(@inject(delay(() => Foo)) public foo: Foo) {}
}

// construction of foo is possible
const foo = container.resolve(Foo);