Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@optional property injection overrides default #1468

Open
haaijman-imagem opened this issue Jun 23, 2022 · 0 comments
Open

@optional property injection overrides default #1468

haaijman-imagem opened this issue Jun 23, 2022 · 0 comments

Comments

@haaijman-imagem
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

No branches or pull requests

1 participant