汽车工厂如何在InversifyJS中工作

时间:2018-12-19 09:32:41

标签: typescript ioc-container inversifyjs

在Autofac中,工厂自动生成工厂用于实例化带有无法从容器中解析的额外道具的类。但是在InversifyJS中则有所不同。有人可以解释我应该/何时在Inverseify中使用自动工厂吗?

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具有名称参数。但我将其传递给工厂。

0 个答案:

没有答案