对于如何使用类型记录中的单例类在构造函数中传递值,我有疑问。
mycode .ts
import {singleton} from "tsyringe";
@singleton()
class Foo {
constructor(data:string)
{
this.data = data
}
}
// some other file
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";
const instance = container.resolve(Foo);如何使用constainer .resolve函数.any在构造函数中传递值,给出了示例代码如何传递该值。
发布于 2019-12-15 16:10:26
您可以执行以下操作将值注入构造函数:
import {singleton} from "tsyringe";
@singleton()
class Foo {
private str: string;
constructor(@inject("SomeName") value: string) {
this.str = value;
}
}
// some other file
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";
const str = "test";
container.register("SomeName", { useValue: str });
const instance = container.resolve(Foo);发布于 2020-05-01 17:14:12
@ answer 1762087回答您的问题,如果您想为每个实例的构造函数提供不同的参数,您可以这样做
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://stackoverflow.com/questions/58926495
复制相似问题