npm package: @codilogy/di
Description: Simple Dependency Injection for Node.js projects written in TypeScript.
Author: Krzysztof Winiarski
Latest version: 1.6.2

# Dependency Injection

[![ko-fi](https://www.ko-fi.com/img/donate_sm.png)](https://ko-fi.com/I2I4IK7B)

Simple dependency injection (DI) library for Node.js projects written in TypeScript. It supports:

- dependency injection through decorators
- namespaced dependency containers

## Installation

In your project install library uisng npm or yarn:

```
npm install --save @codilogy/di
```

## Usage

This is the simplest method, which requires your TypeScript project to be configured with the following options enabled in `tsconfig.json`:

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

Then in your code:

```typescript
import { Injectable, Container } from '@codilogy/di';

@Injectable()
class Engine {}

@Injectable()
class Car {
  constructor(public engine: Engine) {}
}

const car = Container.provide(Car);
```

This is the most basic example when we inject one class into another. When `emitDecoratorMetadata` is set to `true` then no additional code is needed.
`Engine` will be instantiated and injected into `Car`. However if you cannot use this option, code above have to be more expresive:

```typescript
import { Inject, Injectable, Container } from '@codilogy/di';

@Injectable()
class Engine {}

@Injectable()
class Car {
  constructor(@Inject(Engine) public engine: Engine) {}
}
```

or

```typescript
import { Inject, Injectable, Container } from '@codilogy/di';

@Injectable()
class Engine {}

@Injectable()
class Car {
  @Inject(Engine) engine?: Engine;
}
```

We are using `Inject` decorator to insert instance of dependency into provisioned class. Note we can use this decorator as a parameter decorator or property decorator. Althrough final effect will be the same, there is important difference in both approaches. If you decide to use `Inject` on the property, then injection is done after instance of class is created, so any access to this property in the `constructor` will fail. To avoid this, use first example, where `Inject` is used as a property decorator in `constructor`.

### Injecting non-class objects

Sometimes injected value is not a class, but some primitive object like string. Assume we have some `Http` class and we want to provite JWT key to it. Do do so, we can use injection tokens.

In fact we have alredy used them in previous examples. In code `@Inject(Engine)`, `Engine` is the token. All injectable classes can be used as tokens. For other objects we can create custom tokens. Going back to our `Http` class, consider following code:

```typescript
import { Inject, Injectable, Container } from '@codilogy/di';
import { jwtKey } from './configuration';

const JWT = Container.set({ token: 'JWT', factory: () => jwtKey });

@Injectable()
class Http {
  constructor(@Inject(JWT) private jwt: string) {}
}

const http = Container.provide(Http);
```

In comparysion to previous examples we have one new instruction: `Container.set`. It requires to options: a token name and factory, which is used to resolve provided token to value. To better understand this mechanics, check next chapter.

### Usage without decorators

Decorators provide convinient way in TypeScript to write clean code. However, they are only proposal, and for some reason you may be not allowed to use them. That is not a problem. All examples above can be used without decorators, however more code will be needed:

```typescript
import { Container } from '@codilogy/di';

const vin = '5J6RE4H35BL112710';

class Engine {}

class Car {
  vin?: string;

  constructor(public engine: Engine) {}
}

// Create tokens for each object
const ENGINE = Container.set({ token: Engine, factory: () => Engine });
const CAR = Container.set({ token: Car, factory: () => Car });
const VIN = Container.set({ token: 'VIN', factory: () => vin  });

// Define injection points on Car using tokens
Container.provideParameter(CAR, ENGINE, 0);
Container.provideProperty(CAR, VIN, 'vin');

// Provide Car
const car = Container.provide(CAR);
```

## TODO

- [ ] injection groups
- [ ] circular dependencies

## LICENSE

Copyright 2018 Krzysztof Winiarski

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

---

Icons made by <a href="https://www.flaticon.com/authors/dinosoftlabs" title="DinosoftLabs">DinosoftLabs</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a>