Files
Typescript-Dependency-Manager/readme.md

2.1 KiB

Dependency manager

This lib provides a simplistic dependency manager.

Features

  • Resolves dependencies only when they are needed
  • Detect circular dependency
  • Accept any valid Map key as dependency identifier
    • Infer the dependency type from the dependency identifier if the later is a class

Usage

  1. Create a manager:
import { DependencyManager } from 'dependency-manager/mod.ts'

const manager = new DependencyManager()
  1. Register dependencies by giving the manager an identifier and a provider:
manager.register('dependency-identifier', () => 'value');
  1. 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 {}

const a = await manager.resolve(MyDependecy); //< `a` is of type `MyDependency`
const b = await manager.resolve('dependency-identifier'); //< `b` is of type `unknown`
const c = await manager.resolve<number>('dependency-identifier'); //< `c` is of type `number`

Class with private constructor cannot be infered as class and thus need to be explicitly typed when resolved.

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