1.1.0 • Published 4 years ago

typescript-di-container v1.1.0

Weekly downloads
1
License
ISC
Repository
github
Last release
4 years ago

Build Status

Typescript dependency container

This is a simple dependency constructor injection container for classes. Dependencies will be automatically mapped with help of reflect-metadata with the emitted meta information. Each injectable class needs to be decorated with the "Injectable" decorator. This is because typescript only emits decorator metadata for decorated classes.

You will need to add followin lines to your tsconfig.json file

	"emitDecoratorMetadata": true,
	"experimentalDecorators": true,

Usage

import {Container, Injectable} from 'typescript-di-container';

const container = new Container();

@Injectable()
class CacheService {
	constructor() {
	}
}

@Injectable()
class AuthRouter {
	cacheService: CacheService
	constructor(cacheService: CacheService) {
		this.cacheService = cacheService
	}
}

let authRouter = container.get(AuthRouter);

Circular dependency checks

The container will automatically throw an error if a circular dependency is found

import {Injectable, Inject, ForwardRef, Container} from 'typescript-di-container';

@Injectable()
class D {
    constructor(@Inject(new ForwardRef(() => E)) e: E) {}
}
@Injectable()
class E {
    constructor(d: D) {}
}

const container = new Container();

const a = container.get(D);

// will throw error => Circular dependency detected: D -> E -> D

Dealing with modules which have circular dependencies

If you have circular dependency between two modules, one module will be parsed before the other, meaning that when trying to inject the service, you will get an undefined error.

In order to overcome this problem, one can use ForwardRef, like so

import {Injectable, Inject, ForwardRef, Container} from 'typescript-di-container';

@Injectable()
class D {
    constructor(@Inject(new ForwardRef(() => E)) e: E) {}
}
@Injectable()
class E {
    constructor(d: D) {}
}

const container = new Container();

const a = container.get(D);
1.1.0

4 years ago

1.0.13

4 years ago

1.0.12

4 years ago

1.0.9

4 years ago

1.0.11

4 years ago

1.0.10

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago