对于此示例,您可以执行以下操作:
import {singleton} from "tsyringe";
@singleton()
class Foo {
constructor(private value: string) {}
}
// some other file
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";
const str = "test";
container.register<Foo>(Foo,{ useValue: new Foo(str) })
const instance = container.resolve(Foo);
此解决方案有一个问题,因为它需要您在DI框架之外手动创建对象。只要Foo仅对参数值具有依赖关系就可以了,但是如果Foo对另一个类Bar具有依赖关系,则不会将其注入Foo的构造函数中(至少就我所知)。
尽管我还没有找到更好的解决方案,所以在其他人没有更好的答案之前,这可能会解决问题。
,
@ user1762087要回答您的问题,如果您想为每个实例的构造函数提供不同的参数,您可以执行类似的操作
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";
const str = "test";
container.registerInstance("SomeName",{ useValue: str });
const instance = container.resolve(Foo);
// to clear up instances you've registered with registerInstance()
container.clearInstances();
本文链接:https://www.f2er.com/3076418.html