带标签的绑定

原文链接

我们可以通过为绑定设置标签来修复AMBIGUOUS_MATCH错误。该错误的产生原因是:两个以上的具体类被绑定到一个抽象。注意Ninja类的构造函数参数是如何使用@tagged装饰器修饰的:

interface Weapon {}

@injectable()
class Katana implements Weapon {}

@injectable()
class Shuriken implements Weapon {}

interface Ninja {
    katana: Weapon;
    shuriken: Weapon;
}

@injectable()
class Ninja implements Ninja {
    public katana: Weapon;
    public shuriken: Weapon;
    public constructor(
        @inject("Weapon") @tagged("canThrow", false) katana: Weapon,
        @inject("Weapon") @tagged("canThrow", true) shuriken: Weapon
    ) {
        this.katana = katana;
        this.shuriken = shuriken;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

我们将KatanaShuriken绑定到了Weapon,同时添加了whenTargetTagged约束条件来避免出现AMBIGUOUS_MATCH错误:

container.bind<Ninja>(ninjaId).to(Ninja);
container.bind<Weapon>(weaponId).to(Katana).whenTargetTagged("canThrow", false);
container.bind<Weapon>(weaponId).to(Shuriken).whenTargetTagged("canThrow", true);
1
2
3
上次更新: 1/5/2020, 1:11:10 PM