how to pass in parameters for private property from constructor - factory

34 Views Asked by At

I am looking at inversify example, I have question about the Warrior.rank property, assume in a world without DI, I also have another private property called Warrior.salary which can be assigned by Warrior constructor parameter.

In the example, even using factory, the rank property is assigned value because it is public property? What if I don't want to expose it, e.g., a salary property. How can I do that? If it has to be public, what is the point of having a factory to assign the value? Why don't I just get an instance of Warrior without parameters using container.get(), then do Warrior.rank=abc?

To me, making the rank as a public property makes everything ugly, plus with many additional lines of code for factory, what is the point?

let TYPES = {
    IWarrior: Symbol("IWarrior"),
    IWeapon: Symbol("IWeapon"),
    IFactoryOfIWarrior: Symbol("IFactory<IWarrior>")
}

interface IWeapon {}

@injectable()
class Katana implements IWeapon {}

interface IWarrior {
    weapon: IWeapon;
    rank: string;
}

@injectable()
class Warrior implements IWarrior {
    public weapon: IWeapon;
    public rank: string;
    private salary: number; //how to inject this property without exposing it as public property?
    public constructor(
        @inject(TYPES.IWeapon) weapon: IWeapon
    ) {
        this.weapon = weapon;
        this.rank = null; // important!
    }
}

let kernel = new Kernel();
kernel.bind<IWarrior>(TYPES.IWarrior).to(Warrior);
kernel.bind<IWeapon>(TYPES.IWeapon).to(Katana);

kernel.bind<inversify.IFactory<IWarrior>>(TYPES.IFactoryOfIWarrior)
    .toFactory<IWarrior>((context) => {
        return (rank: string) => {
            let warrior = context.kernel.get<IWarrior>(TYPES.IWarrior);
            warrior.rank = rank;
            return warrior;
        };
    });

let warriorFactory = kernel.get<inversify.IFactory<IWarrior>>(TYPES.IFactoryOfIWarrior);

0

There are 0 best solutions below