InversifyJS
InversifyJS copied to clipboard
[Question]: Inject a class with two different implementations
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;
}
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)