https://github.com/ncpa0/tringe
A TypeScript library leveraging decorators to provide a dependency injection mechanism.
https://github.com/ncpa0/tringe
decorators dependency-injection javascript typescript typescript-decorators
Last synced: 3 months ago
JSON representation
A TypeScript library leveraging decorators to provide a dependency injection mechanism.
- Host: GitHub
- URL: https://github.com/ncpa0/tringe
- Owner: ncpa0
- License: mit
- Created: 2023-04-28T13:23:26.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2023-05-08T09:20:31.000Z (about 3 years ago)
- Last Synced: 2025-08-20T13:55:27.271Z (11 months ago)
- Topics: decorators, dependency-injection, javascript, typescript, typescript-decorators
- Language: TypeScript
- Homepage:
- Size: 1.21 MB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# tringe
A TypeScript dependency injection library.
## Usage
```ts
import { Inject, Module } from "tringe";
class MyDependency {
public sayHello() {
console.log("Hello!");
}
}
class MyService extends Module {
@Inject(() => MyDependency)
declare dependency!: MyDependency;
public start() {
this.dependency.sayHello();
}
}
const service = new MyService();
// dependency gets automatically initialized with a `new MyDependency()`
console.assert(service.dependency != null); // true
console.assert(service.dependency instanceof MyDependency); // true
// Inject a different implementation of MyDependency
let helloCount = 0;
class MockDependency {
public sayHello() {
helloCount++;
}
}
// `Module.di()` initializes the module similarly to `new Module`, but can also inject dependencies
const service = MyService.di([MyDependency, MockDependency]); ()
console.assert(service.dependency instanceof MockDependency); // true
```
If the class you want to inject a dependency into already extends another class, you can use a `MixinModule` decorator instead of extending the `Module` class.
```ts
import { Inject, MixinModule } from "tringe";
class MyDependency {
public sayHello() {
console.log("Hello!");
}
}
@MixinModule
class MyService {
@Inject(() => MyDependency)
declare dependency!: MyDependency;
public start() {
this.dependency.sayHello();
}
}
```