【发布时间】:2018-04-02 16:58:57
【问题描述】:
在InversifyJS 中,遵循factory injection guide 和constructor injection guide 中概述的方法分别注入工厂和构造函数比仅使用toDynamicValue 有什么具体优势吗?
【问题讨论】:
标签: typescript dependency-injection inversifyjs
在InversifyJS 中,遵循factory injection guide 和constructor injection guide 中概述的方法分别注入工厂和构造函数比仅使用toDynamicValue 有什么具体优势吗?
【问题讨论】:
标签: typescript dependency-injection inversifyjs
如果您使用toConstructor,您将能够将参数传递给构造函数,但您将无法解析这些参数(除非您也注入它们)。
container.bind<interfaces.Newable<Katana>>("Newable<Katana>")
.toConstructor<Katana>(Katana);
如果您使用toDynamicValue,您将能够将构造函数参数传递给构造函数并使用context 解析这些参数。
container.bind<Katana>("Katana")
.toDynamicValue((context: interfaces.Context) => {
return new Katana(context.container.get("SomeDependency"));
});
如果您使用toFactory,您将能够将构造函数参数传递给构造函数并使用context 解析这些参数,但您还可以根据工厂参数生成不同的输出。
container.bind<interfaces.Factory<Weapon>>("Factory<Weapon>")
.toFactory<Weapon>((context: interfaces.Context) => {
return (throwable: boolean) => {
if (throwable) {
return context.container.getTagged<Weapon>(
"Weapon", "throwable", true
);
} else {
return context.container.getTagged<Weapon>(
"Weapon", "throwable", false
);
}
};
});
【讨论】: