InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

[Question]: Inject a class with two different implementations

Open arielonoriaga opened this issue 4 years ago • 1 comments

How should I do to inject into a class which is consumed in two different instances or more, different implementations of an interface?

Expected Behavior

const types = {
  BasicCarEngine: Symbol.for('BasicCarEngine'),
  AdvancedCarEngine: Symbol.for('AdvancedCarEngine'),
  Car: Symbol.for('Car'),
}

interface IEngine {
  turnOn: () => void;
}

@injectable()
class BasicCarEngine implements IEngine {
  public turnOn(): void {
    // implementation
  }
}

@injectable()
class AdvancedCarEngine implements IEngine {
  public turnOn(): void {
    // implementation
  }
}

interface ICar extends IEngine {
  drive: (direction: string) => void;
}

@injectable()
class Car {
  @inject(Types.BasicCarEngine)
  private _engine: IEngine;
  
  drive(direction: string): void {
    // implementation
  }
}

@injectable()
class Car1 {
  @inject(Types.Car)
  private _car: ICar;
}

@injectable()
class Car2 {
  @inject(Types.Car) //but here with AdvancedCarEngine
  private _car: ICar;
}

arielonoriaga avatar Jul 07 '21 19:07 arielonoriaga

Hey you can use tags to bind to select the right one! [https://github.com/inversify/InversifyJS/blob/master/wiki/tagged_bindings.md](Tagged Bindings)

Focadecombate avatar Dec 27 '21 15:12 Focadecombate