InversifyJS Logger Middleware

3.1.0 · active · verified Wed Apr 22

inversify-logger-middleware is a specialized middleware designed to integrate with InversifyJS, providing a console-based logger for visualizing the dependency injection resolution plan. It intercepts the binding and resolution process within an InversifyJS container, displaying a detailed tree-like structure of service identifiers, bindings, implementation types, scopes, and target metadata. This tool is invaluable for debugging complex dependency graphs and understanding how InversifyJS resolves dependencies. The current stable version is 3.1.0, which is compatible with `inversify@3.x.x`. Its release cadence is tightly coupled with major InversifyJS releases to ensure compatibility. Key differentiators include its deep integration with InversifyJS internals and its clear, visual representation of the container's resolution logic, which helps developers quickly identify misconfigurations or unexpected dependency flows.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up an InversifyJS container with conditional bindings, apply the logger middleware, and resolve dependencies, showing the detailed resolution plan in the console.

import "reflect-metadata";
import { Container, ContainerModule, interfaces } from 'inversify';
import { makeLoggerMiddleware } from 'inversify-logger-middleware';

interface Weapon { attack(): string; }
interface Warrior { fight(): string; sneak(): string; }

class Katana implements Weapon {
  public attack() { return "cut!"; }
}

class Shuriken implements Weapon {
  public attack() { return "throw!"; }
}

class Samurai implements Warrior {
  private _weapon: Weapon;
  constructor(@inversify.inject("Weapon") weapon: Weapon) { this._weapon = weapon; }
  public fight() { return this._weapon.attack(); }
  public sneak() { return ""; }
}

class Ninja implements Warrior {
  private _weapon: Weapon;
  constructor(@inversify.inject("Weapon") weapon: Weapon) { this._weapon = weapon; }
  public fight() { return this._weapon.attack(); }
  public sneak() { return "sneak!"; }
}

const container = new Container();
const logger = makeLoggerMiddleware();
container.applyMiddleware(logger);

const warriorModule = new ContainerModule((bind: interfaces.Bind) => {
    bind<Weapon>("Weapon").to(Katana).whenInjectedInto(Samurai);
    bind<Weapon>("Weapon").to(Shuriken).whenInjectedInto(Ninja);
    bind<Warrior>("Warrior").to(Samurai).whenTargetTagged("canSneak", false);
    bind<Warrior>("Warrior").to(Ninja).whenTargetTagged("canSneak", true);
});

container.load(warriorModule);

// This will now log the resolution plan to the console
const ninja = container.getTagged<Warrior>("Warrior", "canSneak", true);
console.log(ninja.fight());
console.log(ninja.sneak());

const samurai = container.getTagged<Warrior>("Warrior", "canSneak", false);
console.log(samurai.fight());

view raw JSON →