具名绑定
TIP
具名绑定和带标签绑定类似
我们可以通过具名绑定来修复AMBIGUOUS_MATCH
错误。该错误的产生原因是:两个以上的具体类被绑定到一个抽象。注意Ninja
类的构造函数参数是如何使用@named
装饰器修饰的:
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") @named("strong") katana: Weapon,
@inject("Weapon") @named("weak") 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
,同时添加了whenTargetNamed
约束条件来避免产生AMBIGUOUS_MATCH
错误:
container.bind<Ninja>("Ninja").to(Ninja);
container.bind<Weapon>("Weapon").to(Katana).whenTargetNamed("strong");
container.bind<Weapon>("Weapon").to(Shuriken).whenTargetNamed("weak");
1
2
3
2
3