在 Inversify 中,为什么更喜欢 Constructor/Factory 注入而不是 toDynamicValue?
In Inversify, why to prefer Constructor/Factory injection over toDynamicValue?
在InversifyJS, are there any specific advantages of following the approaches outlined in factory injection guide and constructor injection guide for injecting factories and constructors respectively over just using toDynamicValue.
toConstructor
如果您使用 toConstructor
,您将能够将参数传递给构造函数,但您将无法解析这些参数(除非您也注入它们)。
container.bind<interfaces.Newable<Katana>>("Newable<Katana>")
.toConstructor<Katana>(Katana);
toDynamicValue
如果您使用 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
);
}
};
});
在InversifyJS, are there any specific advantages of following the approaches outlined in factory injection guide and constructor injection guide for injecting factories and constructors respectively over just using toDynamicValue.
toConstructor
如果您使用 toConstructor
,您将能够将参数传递给构造函数,但您将无法解析这些参数(除非您也注入它们)。
container.bind<interfaces.Newable<Katana>>("Newable<Katana>")
.toConstructor<Katana>(Katana);
toDynamicValue
如果您使用 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
);
}
};
});