1.0.27 • Published 3 years ago

@anzerr/inject.ts v1.0.27

Weekly downloads
20
License
MIT
Repository
github
Last release
3 years ago

Intro

GitHub Actions status | linter GitHub Actions status | publish GitHub Actions status | test

A simple example of a decorator for dependency injection.

Install

npm install --save git+https://github.com/anzerr/inject.ts.git
npm install --save @anzerr/inject.ts

Example

import 'reflect-metadata';
import {Injectable, Inject, Module} from 'inject.ts';

@Injectable()
class Config {

	constructor() {}

	get() {
		return {
			start: Math.floor(Math.random() * 10)
		};
	}

}

@Injectable()
class Log {
	count: number;

	constructor(@Inject(Config) config: Config) {
		this.count = config.get().start;
	}

	info(...arg) {
		this.count += 1;
		return console.log(this.count, ...arg);
	}

}

class Ping {
	@Inject(Log)
	logger: Log;

	interval: any;

	constructor() {
		this.interval = setInterval(() => this.logger.info('ping'), 5000);
	}

	close() {
		clearInterval(this.interval);
	}

}

new Module([Ping]).build();

Circular Dependency

Best to have zero but you can make them work if you need them after class construction

class A {

	@Inject(B) // 2. start to init "B"
	b: B; // 4. "B" finished construction injected into "A"

	constructor() { // 1. init "A" (added to instance list)
		// don't need "B" now but later in the class usage
	}

}

class B {

	a: A;

	constructor(@Inject(A) a) { // 3. look up "A" (found in instance list)
		// need "A" here
		this.a = a;
	}

}

new Module([A]).build();
1.0.27

3 years ago

1.0.26

4 years ago

1.0.25

4 years ago

1.0.24

4 years ago

1.0.23

4 years ago

1.0.22

5 years ago

1.0.21

5 years ago

1.0.20

5 years ago

1.0.19

5 years ago

1.0.18

5 years ago

1.0.17

5 years ago

1.0.16

5 years ago

1.0.15

5 years ago

1.0.14

5 years ago

1.0.12

6 years ago

1.0.11

6 years ago

1.0.10

6 years ago

1.0.9

6 years ago

1.0.8

6 years ago

1.0.7

6 years ago

1.0.1

6 years ago

1.0.2

6 years ago

1.0.3

6 years ago

1.0.4

6 years ago

1.0.5

6 years ago