在InversifyJS中,遵循工厂注入指南和构造函数注入指南中概述的方法分别注入工厂和构造函数比仅使用toDynamicValue是否有任何特定优势。
6981 次
1 回答
33
构造函数
如果您使用 atoConstructor
您将能够将参数传递给构造函数,但您将无法解析这些参数(除非您也注入它们)。
container.bind<interfaces.Newable<Katana>>("Newable<Katana>")
.toConstructor<Katana>(Katana);
到动态值
如果您使用 atoDynamicValue
您将能够将构造函数参数传递给构造函数并使用context
.
container.bind<Katana>("Katana")
.toDynamicValue((context: interfaces.Context) => {
return new Katana(context.container.get("SomeDependency"));
});
到工厂
如果您使用 atoFactory
您将能够将构造函数参数传递给构造函数并使用解析这些参数,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
);
}
};
});
于 2017-11-01T13:26:41.323 回答