我有一个名为insuranceController的Typescript类,它接受一个多注入参数,如下所示:
@injectable()
export class InsuranceController implements IInsuranceController {
private policies: IInsurancePolicy[];
constructor(@multiInject("IInsurancePolicy") policies: IInsurancePolicy[]) {
this.policies = policies;
}
}
insurancePolicy类需要一个数字作为构造函数参数
@injectable()
export class InsurancePolicy implements IInsurancePolicy{
constructor(public index: number) {
}
}
所以我按如下方式创建绑定:
this.container.bind<IInsurancePolicy>("IInsurancePolicy").toConstantValue(new InsurancePolicy(0));
this.container.bind<IInsurancePolicy>("IInsurancePolicy").toConstantValue(new InsurancePolicy(1));
this.container.bind<IInsurancePolicy>("IInsurancePolicy").toConstantValue(new InsurancePolicy(2));
这一切都很棒。但是我现在想在insurancePolicy类中注入第二个参数:
constructor(public index: number,
@inject("IIntakeLayout") intakeLayout: IIntakeLayout) {
}
我该怎么做?我已经尝试过查看这里概述的技术:InversifyJS Injecting Literal Constructor Parameters,但我看不出它们如何在多项目场景中工作。请注意,InsuranceController本身是注入的,因此我无法手动创建它。我应该如何使用Inversify进行此操作?
答案 0 :(得分:2)
您可以创建使用toDynamicValue
的辅助函数:
function registerInsurancePolicy(ctr: Container, id: number) {
ctr.bind<IInsurancePolicy>("IInsurancePolicy")
.toDynamicValue((context) => {
cosnt intakeLayout = context.container.get<IIntakeLayout>("IIntakeLayout");
return new InsurancePolicy(id, intakeLayout);
})
.inSingletonScope();
}
然后使用帮助器:
registerInsurancePolicy(this.container, 1);
registerInsurancePolicy(this.container, 2);
registerInsurancePolicy(this.container, 3);