0.5.0 • Published 12 months ago

reflective-dependency-injection v0.5.0

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

Reflective Dependency Injection

Dependency injection based on TypeScript's experimental support for stage 2 decorators and metadata.

  • Constructor-based injection
  • Asynchronous support
  • Error detection
    • Circular dependency
    • Lifetime mismatch

Getting Started

If you are unfamiliar with decorators and metadata, I recommend checking out the TypeScript documentation and TC39's decorator proposal documentation.

Prerequisites

The following versions of Node.js and TypeScript are required:

  • Node.js 20 or higher
  • TypeScript 4.7 or higher

This package is pure ESM, and you must configure your project to use the ESM package.

Installation

1. Install the package using npm

npm install reflective-dependency-injection

2. Set compiler options in your tsconfig.json to enable experimental support for stage 2 decorators and metadata

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    }
}

Usage

Let's take a look at the basic usage through the following steps.

1. Declare dependencies

First you need to declare your dependencies.

Decorate a class with the @Injectable decorator to make the class injectable.

Use the InjectionToken class as the identifier for non-class dependencies, and decorate the @Inject decorator to specify the dependency identifier.

const GREETING: InjectionToken<string> = new InjectionToken('greeting');

@Injectable()
class Greeter {
    public constructor(
        @Inject(GREETING)
        public readonly greeting: string,
    ) { }

    public greet(): string {
        return `Hello, ${this.greeting}`;
    }
}

2. Create an injector

Create an injector with providers that provide the declared dependencies.

Use the provide function for type safety.

const injector: Injector = new Injector([
    provide({
        identifier: Greeter,
        useClass: Greeter,
    }),
    provide({
        identifier: GREETING,
        useValue: 'world!',
    }),
]);

3. Resolve dependencies

The injector resolves the dependency graph and returns an instance of the dependency.

const greeter: Greeter = await injector.get(Greeter);

expect(greeter.greet()).toBe('Hello, world!');

License

Distributed under the MIT License. See the LICENSE file for more details.

0.5.0

12 months ago

0.4.3

1 year ago

0.4.2

1 year ago

0.4.1

1 year ago

0.4.0

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago