如何在Tsyringe中实现单例

问题描述 投票:0回答:2

我在实现单例时遇到了麻烦,因为标记为 @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");
  }
}
// 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");
  }
}
// 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);

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

singleton tsyringe
2个回答
10
投票

单例应按如下方式注册

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

3
投票

我认为你让你的生活变得更加困难。我发现您所做的事情以及您提出的解决方案存在一些问题。这是 @singleton() 装饰器的

源代码

function singleton<T>(): (target: constructor<T>) => void {
  return function(target: constructor<T>): void {
    injectable()(target);
    globalContainer.registerSingleton(target);
  };
}
  • 首先,你不需要用
    @injectable()
    来装饰,因为tsyringe已经添加了
    @singleton()
  • 最后,如果您不注册
    Foo
    Bar
    ,它们将在
    { lifecycle: Lifecycle.Singleton }
    函数中自动注册为单例(当然,已经设置了
    globalContainer.registerSingleton(target)
    选项)。
© www.soinside.com 2019 - 2024. All rights reserved.