Reputation: 761
I have a Typescript class called insuranceController that accepts a multi inject parameter like so:
@injectable()
export class InsuranceController implements IInsuranceController {
private policies: IInsurancePolicy[];
constructor(@multiInject("IInsurancePolicy") policies: IInsurancePolicy[]) {
this.policies = policies;
}
}
The insurancePolicy class needs a number as a constructor parameter
@injectable()
export class InsurancePolicy implements IInsurancePolicy{
constructor(public index: number) {
}
}
So I create the bindings as follows:
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));
This all works great. However I now want to inject a second parameter into the insurancePolicy class:
constructor(public index: number,
@inject("IIntakeLayout") intakeLayout: IIntakeLayout) {
}
How can I do this? I have tried looking the techniques outlined here: InversifyJS Injecting Literal Constructor Parameters, but I can't see how they would work in a multiinject scenario. Note that the InsuranceController itself is injected so I can't create it manually. How should I go about this using Inversify?
Upvotes: 1
Views: 2038
Reputation: 24941
You can create a helper function that uses 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();
}
Then use the helper:
registerInsurancePolicy(this.container, 1);
registerInsurancePolicy(this.container, 2);
registerInsurancePolicy(this.container, 3);
Upvotes: 2