75 lines
2.2 KiB
Markdown
75 lines
2.2 KiB
Markdown
# Dependency manager
|
|
|
|
This lib provides a simplistic dependency manager.
|
|
|
|
## Features
|
|
|
|
- Resolves dependencies only when they are needed
|
|
- Detects circular dependency
|
|
- Strong type support
|
|
|
|
The [previous major release](https://git.chpt.dev/Chappatte/Typescript-Dependency-Manager/src/tag/v1.1.1) used to allow asynchronous dependencies and the use of class as identifier, but those features were replaced by the `Symbol` identifier to keep the lib dead simple.
|
|
|
|
## Basic usage
|
|
|
|
```typescript
|
|
import { DependencyManager } from 'dependency-manager/mod.ts'
|
|
|
|
// 1. Create a manager:
|
|
const manager = new DependencyManager();
|
|
|
|
// 2. Create a dependency (a provider and an identifier):
|
|
const value = 'foo';
|
|
const provider = () => value;
|
|
const identifier = Symbol() as DependencyIdentifier<typeof value>;
|
|
|
|
// 3. Register the dependency:
|
|
manager.register(identifier, provider);
|
|
|
|
// 4. Anywhere in your code, inject the resolved dependency value:
|
|
const value = await manager.inject(identifier);
|
|
```
|
|
|
|
## Identifier
|
|
|
|
An identifier is a uniq value used by the dependency manager to store and retrieve the dependency.
|
|
|
|
The `DependencyIdentifier` type allow the return value of the `inject` method to be fully typed,
|
|
|
|
## Providers
|
|
|
|
A dependency is rarely just a simple value like in the basic usage code and often rely on other dependencies.
|
|
|
|
That's why the `register` method takes a function (that we call the dependency `provider`) who's role is to build the dependency.
|
|
|
|
That function receive a uniq parameter: The dependency manager.
|
|
That way it is possible to inject dependencies inside it:
|
|
|
|
```typescript
|
|
function providerA() {
|
|
return 'foo'
|
|
}
|
|
const identifierA = Symbol() as DependencyIdentifier<ReturnType<typeof providerA>>;
|
|
|
|
function providerB(manager: DependencyManager) {
|
|
const a = manager.inject(identifierA);
|
|
return `The value is: ${a}`;
|
|
}
|
|
const identifierB = Symbol() as DependencyIdentifier<ReturnType<typeof providerB>>;
|
|
|
|
manager.register(identifierA, providerA);
|
|
manager.register(identifierB, providerB);
|
|
|
|
// ...
|
|
|
|
const b = manager.inject(identifierB); // "The value is: foo"
|
|
```
|
|
|
|
## Errors
|
|
|
|
The `register` method throw an error if:
|
|
- the dependency is already registred.
|
|
|
|
The `inject` method throw an error if:
|
|
- the dependency is not registred.
|
|
- a circular dependency is detected |