Inversify Binding Decorators

4.0.0 · active · verified Sun Apr 19

Inversify Binding Decorators is a utility library for InversifyJS, a powerful Inversion of Control (IoC) container for TypeScript and JavaScript applications. It simplifies the process of declaring dependency injection bindings by allowing developers to use ES2016 decorators directly on classes. This contrasts with InversifyJS's standard fluent API for binding. The current stable version is 4.0.0, which typically aligns with major versions of InversifyJS itself, indicating a release cadence tied to its core dependency. Its primary differentiator is the `@provide` decorator, enabling a more declarative and less verbose way to register components with the InversifyJS container, particularly useful in large applications with many services.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `@provide` decorator to declare bindings and `buildProviderModule` to load them into an InversifyJS container.

import { injectable, Container } from "inversify";
import { provide, buildProviderModule } from "inversify-binding-decorators";
import "reflect-metadata"; // Must be imported once at the application entry point

interface Weapon { hit(): string; }
interface ThrowableWeapon { throw(): string; }

@injectable()
@provide(Katana)
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@injectable()
@provide(Shuriken)
class Shuriken implements ThrowableWeapon {
    public throw() {
        return "hit!";
    }
}

const container = new Container();
// Load all bindings declared via @provide decorators
container.load(buildProviderModule());

// Resolve instances from the container
const katana = container.get<Weapon>(Katana);
const shuriken = container.get<ThrowableWeapon>(Shuriken);

console.log(`Katana: ${katana.hit()}`);
console.log(`Shuriken: ${shuriken.throw()}`);

view raw JSON →