如何在 Tsyringe 中实现单例

Cyb*_*igy 4 singleton tsyringe

我在实现单例时遇到问题,因为标记为 @singleton() 的类正在每个resolve() 上重新创建。

这是例子

// Foo.ts This is singleton and and must be created only once
import { injectable, singleton } from "tsyringe";

@injectable()
@singleton()
export class Foo {
  constructor() {
    console.log("Constractor of Foo");
  }
}
Run Code Online (Sandbox Code Playgroud)
// Bar.ts this is Bar and should be created every time. It uses the singleton
import { inject, injectable, Lifecycle, scoped } from "tsyringe";
import { Foo } from "./Foo";

@injectable()
export class Bar {
  constructor(@inject("Foo") private foo: Foo) {
    console.log("Constractor of Bar");
  }
}
Run Code Online (Sandbox Code Playgroud)
// main.ts this is resolving Bar two times.
// expected output:
// Constractor of Foo
// Constractor of Bar
// Constractor of Bar

// Actual output:
// Constractor of Foo
// Constractor of Bar
// Constractor of Foo
// Constractor of Bar

import "reflect-metadata";
import { container } from "tsyringe";
import { Bar } from "./Bar";
import { Foo } from "./Foo";

container.register("Foo", { useClass: Foo });
container.register("Bar", { useClass: Bar });

const instance = container.resolve(Bar);
const instance1 = container.resolve(Bar);

Run Code Online (Sandbox Code Playgroud)

我怎样才能获得所需的行为?

Cyb*_*igy 8

Singleton应该注册如下

container.register(
  "Foo",
  { useClass: Foo },
  { lifecycle: Lifecycle.Singleton } // <- this is important
);
Run Code Online (Sandbox Code Playgroud)