Typescript 在Inversify中,为什么选择构造函数/工厂注入而不是动态值?
在中,与仅使用相比,遵循和中分别针对注射工厂和施工人员概述的方法是否有任何具体优势。toConstructor 如果使用Typescript 在Inversify中,为什么选择构造函数/工厂注入而不是动态值?,typescript,dependency-injection,inversifyjs,Typescript,Dependency Injection,Inversifyjs,在中,与仅使用相比,遵循和中分别针对注射工厂和施工人员概述的方法是否有任何具体优势。toConstructor 如果使用toConstructor,则可以将参数传递给构造函数,但无法解析这些参数(除非同时注入它们) 托福工厂 如果使用toFactory,则可以将构造函数参数传递给构造函数,并使用上下文解决这些参数,但也可以基于工厂参数生成不同的输出 container.bind<interfaces.Factory<Weapon>>("Factory<Weapon&
toConstructor
,则可以将参数传递给构造函数,但无法解析这些参数(除非同时注入它们)
托福工厂
如果使用toFactory
,则可以将构造函数参数传递给构造函数,并使用上下文解决这些参数,但也可以基于工厂参数生成不同的输出
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
);
}
};
});
container.bind(“工厂”)
.toFactory((上下文:interfaces.context)=>{
返回(可丢弃:布尔)=>{
如果(可丢弃){
返回context.container.gettaged(
“武器”,“可扔掉的”,真的
);
}否则{
返回context.container.gettaged(
“武器”,“可丢弃的”,假的
);
}
};
});
非常感谢您清晰明了的解释。同时也感谢您在inversify上所做的出色工作。
container.bind<Katana>("Katana")
.toDynamicValue((context: interfaces.Context) => {
return new Katana(context.container.get("SomeDependency"));
});
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
);
}
};
});