2

在 Autofac 中,auto-factory 是用于实例化具有无法从容器中解析的额外道具的类的工厂。但在 InversifyJS 中,情况有所不同。有人可以解释我应该如何/何时在 Inversify 中使用自动工厂吗?

export class Main {
    private container: Container;

    constructor() {
        this.container = new Container();
        this.container.bind('Cat').to(Cat);
        this.container.bind('Kitty').to(Kitty);
        this.container.bind<Factory<Kitty>>('Factory<Kitty>').toAutoFactory('Kitty');
    }

    public run(): string {
        let cat = this.container.get<Cat>('Cat');
        return cat.meow();
    }
}

@injectable()
export class Cat {
    private kitty: Kitty;

    constructor(
        @inject('Factory<Kitty>') kittyFactory: Factory<Kitty>,
    ) {
        this.kitty = kittyFactory('joe') as Kitty;
    }

    public meow(): string {
        return this.kitty.meow();
    }
}

@injectable()
export class Kitty {
    private readonly name: string;

    constructor(name: string) {
        this.name = name;
    }

    meow(): string {
        return this.name;
    }
}

它无法解析 Kitty,因为 Kitty 有 name 参数。但我把它传给工厂。

4

0 回答 0