Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/lulusir/di
A simple Dependency Injection
https://github.com/lulusir/di
dependency-injection injection ioc ioc-container typescript
Last synced: about 2 months ago
JSON representation
A simple Dependency Injection
- Host: GitHub
- URL: https://github.com/lulusir/di
- Owner: lulusir
- Created: 2022-03-07T13:59:19.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2023-03-10T03:30:12.000Z (almost 2 years ago)
- Last Synced: 2024-06-20T10:23:46.381Z (6 months ago)
- Topics: dependency-injection, injection, ioc, ioc-container, typescript
- Language: TypeScript
- Homepage:
- Size: 537 KB
- Stars: 7
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
The interface refers to [TSyringe](https://github.com/Microsoft/tsyringe)
## install
```bash
npm install @lujs/di
```### api
#### injectable()
The injectable decorator marks a class as injectable, meaning that its dependencies can be resolved and injected by the Container.
```typescript
import { injectable, container } from './injectable';
class B {
name = 'b'
}@injectable()
class A {
constructor(b: B) {}
}const a = container.resolve(A)
console.log(a.b) // 'b'
```#### singleton()
The singleton decorator marks a class as a singleton, meaning that the same instance will be used every time
```typescript
import { singleton, container } from './injectable';
class B {
name = 'b'
}@singleton()
class A {
constructor(b: B) {}
}const a1 = container.resolve(A)
const a2 = container.resolve(A)console.log(a1 === a2) // true
```
#### inject()
The inject decorator marks a constructor parameter as a dependency to be resolved and injected by the Container.
```typescript
import { inject, InjectToken } from './injectable';const token = Symbol('token');
interface B {}@injectable()
class A {
constructor(@inject(token) public b: B) {}_() {
console.log(this.b);
}
}class B1 implements B {}
container.register(token, { useClass: B1 });
const a = container.resolve(A);
expect(a.b).toBeDefined();
expect(a.b).toBeInstanceOf(B1);
```
### circular dependency
Use proxy objects to solve circular dependency problems. But you should approach this from the perspective of code design
```typescript
@injectable()
export class CircleA {
constructor(@inject(delay(() => CircleB)) public b: CircleB) {}
}@injectable()
export class CircleB {
constructor(@inject(delay(() => CircleA)) public a: CircleA) {}
}
```