0

我希望能够简单地指定需要什么而不添加字符串或符号。这似乎适用于声明绑定:

container.bind<Weapon>(Shuriken);

但是,如果我不使用@inject并且在注入时不知道要放入什么,则会出现运行时错误:

public constructor(
    @inject() weapon: Weapon // compile-time error
) {
4

1 回答 1

0

当你使用一个接口(我假设它Weapon是一个接口)时,你需要确保在声明绑定时使用相同的 ID:

container.bind<Weapon>(Shuriken).toSelf();

然后你声明注入:

@injectable()
class SomeClass {
    public constructor(
        @inject(Shuriken) weapon: Weapon; // Use the right ID!
    ) {

但是,使用该类消除了依赖注入的好处。如果你想让你使用类,你实际上可以做一些更简单的事情:

@injectable()
class SomeClass {
    public constructor(
        weapon: Shuriken; // Use the class as Type!
    ) {

推荐的解决方案是使用字符串或符号作为 ID:

const TYPE = { Weapon: "Weapon" };

container.bind<Weapon>(TYPE.Weapon).to(Shuriken);

@injectable()
class SomeClass {
    public constructor(
        @inject(TYPE.Weapon) weapon: Weapon;
    ) {
于 2018-03-20T15:54:04.037 回答