Skip to main content

Dependency inversion

In order to apply the dependency inversion principle, we can rely on 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 this way we can provide interface implementations in a way the dependent class is not aware of the dependency implementation details.

note

Even if symbols are suggested for this purpose, InversifyJS supports the usage of Classes and string literals as service identifiers as well.