Skip to main content
Version: 6.x

Dependency inversion

To apply the dependency inversion principle, you can use injection symbols:

import { Container, inject, injectable } from 'inversify';

interface Weapon {
damage: number;
}

const weaponServiceId: symbol = Symbol.for('WeaponServiceId');

@injectable()
class Katana {
public readonly damage: number = 10;
}

@injectable()
class Ninja {
constructor(
@inject(weaponServiceId)
public readonly weapon: Weapon,
) {}
}

const container: Container = new Container();

container.bind(Ninja).toSelf();
container.bind(weaponServiceId).to(Katana);

const ninja: Ninja = container.get(Ninja);

console.log(ninja.weapon.damage);

By using symbols, you can provide interface implementations in a way that the dependent class is not aware of the dependency implementation details.

note

Although symbols are recommended for this purpose, InversifyJS also supports using Classes and string literals as service identifiers.