简体   繁体   中英

Using Inversify to do a Multiinject of a class with constant and injected parameters

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM