Deviopath › TypeScript

Dependency Injection Container

Hard · Classes

Implement a dependency injection Container.

- register(token, provider) stores how to build token: its deps (other tokens), a factory and a lifetime.

- resolve(token) resolves every dependency in order, then returns factory(...deps).

- A "singleton" is built once and then reused everywhere. A "transient" is built again every time it is resolved, also as a dependency.

- Unknown token: throw Error("No provider for <token>: <chain>"); the chain lists the tokens from the requested one, e.g. "No provider for db: service -> repo -> db".

- A token that depends on itself (directly or not): throw Error("Cycle detected: <chain>"), e.g. "Cycle detected: a -> b -> a".

- If a factory throws, let the error through and cache nothing.

The driver runContainer is already written; instances are strings like "repo#2(db#1)".

Next: Matrix Class and Fast Power