InversifyJS
InversifyJS copied to clipboard
@optional property injection overrides default
Currently the @optional tag overrides class properties defined with typescript-style default values:
@injectable()
class Ninja {
@inject(Weapon) @optional() weapon: Weapon = new Katana();
....
}
this currently sets the weapon property to undefined if no Weapon is present in the container.
Expected Behavior
injection does not override the default and results in the weapon property being set to new Katana().
Current Behavior
injection overrides the default property to undefined instead.
Possible Solution
see PR #1467
Steps to Reproduce (for bugs)
@injectable()
@injectable()
class Shuriken {
public name: string;
public constructor() {
this.name = 'Shuriken';
}
}
@injectable()
class Ninja {
@inject("Shuriken") @optional() public shuriken: Shuriken = {
name: "DefaultShuriken",
};
}
const container = new Container();
container.bind<Ninja>('Ninja').to(Ninja);
let ninja = container.get<Ninja>('Ninja');
expect(ninja.shuriken.name).to.eql('DefaultShuriken');
container.bind<Shuriken>('Shuriken').to(Shuriken);
ninja = container.get<Ninja>('Ninja');
expect(ninja.shuriken.name).to.eql('Shuriken');
}
Context
@optional has become much less for property injection useful because of this bug. I know property injection is not the best kind of injection pattern but it seems like an easy fix.