2

In Autofac, auto-factory is generated factory for instantiating of classes with extra props which are cannot be resolved from container. But in InversifyJS it is something different. Could someone explain how / when should I use auto-factory in 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;
    }
}

And it cannot resolve Kitty, because Kitty has name parameter. But I pass it to factory.

Igor Babkin
  • 509
  • 2
  • 6
  • 14

0 Answers0