# @typemon/di

> Dependency Injection for TypeScript

Latest version **4.0.0** (published 2019-03-11) · MIT license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install @typemon/di
pnpm add @typemon/di
yarn add @typemon/di
bun add @typemon/di
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 4.0.0 |
| Published | 2019-03-11 |
| First published | 2019-02-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 59.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Monster Space Network |
| Maintainers | monsterspace.network |
| Keywords | monster-space-network, typemon, di, dependency-injection, dependency, dependencies, ioc, inversion-of-control, ioc-container, inversion-of-control-container, container, injectable, injection, inject, injector, async-injector, hierarchical, hierarchical-injector, factory, async-factory |

## Links

- npm: https://www.npmjs.com/package/@typemon/di
- Repository: https://gitlab.com/monster-space-network/typemon/di
- npm.io page: https://npm.io/package/@typemon/di

## Dependencies (2)

- [@typemon/types](https://npm.io/package/@typemon/types.md) ^2.2.0
- [reflect-metadata](https://npm.io/package/reflect-metadata.md) ^0.1.13

## Alternatives

- [memory-cache](https://npm.io/package/memory-cache.md) — 795.0K weekly downloads
- [@httptoolkit/proxy-agent](https://npm.io/package/@httptoolkit/proxy-agent.md) — 11.2K weekly downloads
- [express-cache-controller](https://npm.io/package/express-cache-controller.md) — 5.3K weekly downloads
- [http-cache-middleware](https://npm.io/package/http-cache-middleware.md) — 4.5K weekly downloads
- [cache2](https://npm.io/package/cache2.md) — 1.5K weekly downloads

## Recent versions

- 4.0.0 (latest) — 2019-03-11
- 4.0.0-beta.1 — 2019-03-10
- 3.1.1 — 2019-03-03
- 3.1.0 — 2019-03-03
- 3.0.0 — 2019-02-28
- 2.2.1 — 2019-02-27
- 2.2.0 — 2019-02-27
- 2.1.0 — 2019-02-27
- 2.0.0 — 2019-02-27
- 1.0.0 — 2019-02-25

## README

# DI - [![npm-version](https://img.shields.io/npm/v/@typemon/di.svg)](https://www.npmjs.com/package/@typemon/di) [![npm-downloads](https://img.shields.io/npm/dt/@typemon/di.svg)](https://www.npmjs.com/package/@typemon/di)
> 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](https://gitlab.com/monster-space-network/typemon/di/wikis/home) for detailed feature descriptions, APIs and ecosystem.



## Installation
> This library uses [`reflect-metadata`](https://github.com/rbuckton/reflect-metadata).

```
$ npm install @typemon/di
```
```typescript
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.

```typescript
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`.

```typescript
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.

```typescript
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);
```
```typescript
Monster { name: 'Typemon', level: 1 }
Adventurer {
    name: 'Typemon\'s Master',
    level: 16,
    items: [ 'sword', 'magic-boots' ],
    pet: Monster { name: 'Typemon', level: 1 } }
}
```

---
_Source: https://npm.io/package/@typemon/di · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
