我在实现单例时遇到了困难,因为标记为@ singleton ()的类是在每一个解析()上重新创建的。
下面是一个例子
// 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);我怎样才能得到想要的行为?
发布于 2021-03-31 08:19:44
单身人士应按以下方式登记:
container.register(
"Foo",
{ useClass: Foo },
{ lifecycle: Lifecycle.Singleton } // <- this is important
);发布于 2021-05-04 14:30:19
我觉得你让你的生活变得更艰难了。我看到你所做的事情和你提出的解决方案有几处不对。下面是用于源代码装饰器的@singleton():
function singleton<T>(): (target: constructor<T>) => void {
return function(target: constructor<T>): void {
injectable()(target);
globalContainer.registerSingleton(target);
};
}@injectable()来装饰,因为注射器已经添加了@singleton()。Foo和Bar,它们将自动注册为globalContainer.registerSingleton(target)函数中的单例(当然已经设置了{ lifecycle: Lifecycle.Singleton }选项)。https://stackoverflow.com/questions/66871593
复制相似问题