4.0.0 • Published 5 years ago

@typemon/di v4.0.0

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
5 years ago

DI - npm-version npm-downloads

Dependency Injection for TypeScript

About

The development experience with OOP is fantastic. But there is a dark side. One of them is dependency management. Most solves the problem by injecting dependencies through the IoC Container. We have tried and tried many libraries that have implemented functions but could not be satisfied. So we made our own style. Although the function is simple, I hope it helps. I got a lot of inspiration from the dependency injection structure of the Angular :heart:.

Features

  • See the Wiki for detailed feature descriptions, APIs and ecosystem.

Installation

This library uses reflect-metadata.

$ npm install @typemon/di
import {
    /* Injector classes */
    Injector, AsyncInjector,
    ResolutionStrategy,

    /* Decorators */
    Injectable, Inject, Optional, Self, SkipSelf,

    /* Injection token class */
    InjectionToken,

    /* Providers */
    Provider, SyncProvider, AsyncProvider,
    ValueProvider,
    FactoryProvider,
    AsyncFactoryProvider,
    ClassProvider,
    ConstructorProvider,
    ExistingProvider,

    /* error classes */
    EmptyStringIdentifierError,
    ProviderNotFoundError
} from '@typemon/di';

Configure the TypeScript compile options.

The following options must be set to true.

  • experimentalDecorators
  • emitDecoratorMetadata

Usage

Design dependencies.

  • All class dependencies that the injector manages must use the Injectable decorator.
  • Use injection tokens and decorators as needed.
const MONSTER_NAME_TOKEN: InjectionToken<string> = new InjectionToken('Monster.Name');
const MONSTER_LEVEL_TOKEN: InjectionToken<number> = new InjectionToken('Monster.Level');

@Injectable()
class Monster {
    public constructor(
        @Inject(MONSTER_NAME_TOKEN) public readonly name: string,
        @Inject(MONSTER_LEVEL_TOKEN) @Optional() public readonly level: number = 1
    ) { }

    public eat(): void {
        console.log('Pet: Yum Yum.');
    }

    public sleep(): void {
        console.log('Pet: zzZ zzZ.');
    }
}

const ADVENTURER_NAME_TOKEN: InjectionToken<string> = new InjectionToken('Adventurer.Name');
const ADVENTURER_LEVEL_TOKEN: InjectionToken<number> = new InjectionToken('Adventurer.Level');
const ADVENTURER_ITEMS_TOKEN: InjectionToken<string> = new InjectionToken('Adventurer.Items');

@Injectable()
class Adventurer {
    public constructor(
        @Inject(ADVENTURER_NAME_TOKEN) public readonly name: string,
        @Inject(ADVENTURER_LEVEL_TOKEN) @Optional() public readonly level: number = 1,
        @Inject(ADVENTURER_ITEMS_TOKEN) public readonly items: ReadonlyArray<string>,
        public readonly pet: Monster
    ) { }

    public eat(): void {
        console.log('Adventurer: Yum Yum.');
    }

    public sleepWithPet(): void {
        this.pet.sleep();

        console.log('Adventurer: zzZ zzZ.');
    }
}

Create an injector.

  • Use the create static method to create the injector.
  • How you create an asynchronous injector depends on your chosen resolution strategy.
const injector: Injector = Injector.create([
    Provider.useValue({
        identifier: MONSTER_NAME_TOKEN,
        value: 'Typemon'
    }),
    Provider.use(Monster)
]);
const asyncInjector: AsyncInjector = AsyncInjector.create(
    [
        Provider.useFactory({
            identifier: ADVENTURER_NAME_TOKEN,
            callback: (pet: Monster): string => `${pet.name}'s Master`,
            dependencies: [Monster]
        }),
        Provider.useAsyncFactory({
            identifier: ADVENTURER_LEVEL_TOKEN,
            callback: (pet: Monster, name: string): Promise<number> => {
                return new Promise((resolve: (level: number) => void): void => {
                    setTimeout((): void => resolve(pet.level * name.length), 3000);
                });
            },
            dependencies: [Monster, ADVENTURER_NAME_TOKEN]
        }),
        Provider.useValue({
            identifier: ADVENTURER_ITEMS_TOKEN,
            value: 'sword',
            multiple: true
        }),
        Provider.useAsyncFactory({
            identifier: ADVENTURER_ITEMS_TOKEN,
            callback: async (level: number): Promise<string> => level >= 10 ? 'magic-boots' : 'boots',
            dependencies: [ADVENTURER_LEVEL_TOKEN],
            multiple: true
        }),
        Provider.use(Adventurer)
    ],
    {
        parent: injector,
        resolutionStrategy: ResolutionStrategy.Lazy
    }
);

Get a dependency from the injector.

  • The resolved dependency is cached and the cached value is returned in the next request.
const monster: Monster = injector.get(Monster);
const adventurer: Adventurer = await asyncInjector.get(Adventurer);

adventurer.pet === monster; // true
adventurer.eat();           // Adventurer: Yum Yum.
adventurer.sleepWithPet();  // Pet: zzZ zzZ. / Adventurer: zzZ zzZ.

console.log(monster, adventurer);
Monster { name: 'Typemon', level: 1 }
Adventurer {
    name: 'Typemon\'s Master',
    level: 16,
    items: [ 'sword', 'magic-boots' ],
    pet: Monster { name: 'Typemon', level: 1 } }
}