@frank-mayer/dilight
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

dilight

Lightweight ES5 compatible Dependency Injection Library

License: MIT

Test

Lint

Installation

npm install @frank-mayer/dilight

Usage

Construct a new DIContainer and register your services.

Keep in mind that the add methods return the same container instance (no new instance is created), but the type is updated with the new registered service.

Don't do this

const container = new DIContainer();
container.addTransient(Foo, "Foo");
container.addTransient(Bar, "Bar");

Do this

const container = new DIContainer()
  .addTransient(Foo, "Foo")
  .addTransient(Bar, "Bar");

Interface

You can also provide a different type for the service.

const container = new DIContainer()
  .addTransient<Logger>(FileLogger, "Logger");

Decorators

const container = new DIContainer()
  .addTransient(Foo, "Foo");

const inject = makeDecorator(container);

class Foo {
  @inject("Logger")
  private logger: Logger;
}

Full Example

import { DIContainer } from "@frank-mayer/dilight";

// Demo classes

class Foo { }

class Bar { }

class Baz {
  constructor(param: number) { }
}

interface ILogger {
  log(message: string): void;
}

class ConsoleLogger implements ILogger {
  log(message: string): void {
    console.log(message);
  }
}

// register services

export const container = new DIContainer()
  .addTransient(Foo, "Foo")
  .addSingleton(Bar, "Bar")
  .addFactory(() => new Baz(Math.random()), "Baz")
  .addSingleton<ILogger>(ConsoleLogger, "ILogger");

// resolve services

const foo: Foo = container.resolve("Foo");
const bar: Bar = container.resolve("Bar");
const baz: Baz = container.resolve("Baz");
const baz: ILogger = container.resolve("ILogger");

Readme

Keywords

none

Package Sidebar

Install

npm i @frank-mayer/dilight

Weekly Downloads

1

Version

1.1.1

License

MIT

Unpacked Size

33.1 kB

Total Files

14

Last publish

Collaborators

  • frank-mayer