带标签的绑定
我们可以通过为绑定设置标签来修复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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
我们将Katana
和Shuriken
绑定到了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
2
3