2.2 KiB
2.2 KiB
Dependency manager
This lib provides a simplistic dependency manager.
Features
- Resolves dependencies only when they are needed
- Detect circular dependency
- Accept any valid
Mapkey as dependency identifier- Infer the dependency type from the dependency identifier if the later is a class
Usage
- Create a manager:
import { DependencyManager } from 'dependency-manager/mod.ts'
const manager = new DependencyManager()
- Register dependencies by giving the manager an identifier and a provider:
manager.register('dependency-identifier', () => 'value');
- Get the dependency by giving the manager its identifier (always asynchrone):
const value = await manager.resolve('dependency-identifier');
Providers
Providers are functions that are called when resolving the dependency for the first time. They receive the dependency manager as parameter, and should return the dependency value, or a promise that resolves to it.
Example of the registration of a dependency which provider uses another dependency:
async function provider(manager: DependencyManager) {
const value = await manager.resolve('dependencyIdentifier');
return `The value is: ${valueA}`;
}
manager.register('other-identifier', provider);
Identifiers and typing
Any valid Map key can be used as identifier, but using a class allow the return value of the resolve method to be automatically typed:
class MyDependency {}
manager.register(MyDependency, () => new MyDependency());
const a = await manager.resolve(MyDependecy); //< `a` is of type `MyDependency`
Otherwise you can provide the type as type argument:
function provider() {
return 'foo'
}
manager.register('my-dependency-identifier', provider);
const a = await manager.resolve('my-dependency-identifier'); //< `a` is of type `unknown`
const b = await manager.resolve<string>('my-dependency-identifier'); //< `b` is of type `string`
Errors
The register method throw an error if:
- the name is already used.
The resolve method throw an error if:
- the name doesn't exist (if no module has been registred with the given name).
- a circular dependency is detected