Dependency Injection Container Typed

Implement a typed DI container with token-based registration and resolution for testable service wiring.

TypescriptConfig Management

Code

typescriptsnippet
1 line
type Token<T>=symbol&{__type:T};export function token<T>(name:string):Token<T>{return Symbol(name)as Token<T>;}export class Container{private registry=new Map<symbol,unknown>();register<T>(t:Token<T>,factory:(c:Container)=>T):void{this.registry.set(t as symbol,factory);}resolve<T>(t:Token<T>):T{const f=this.registry.get(t as symbol)as((c:Container)=>T)|undefined;if(!f)throw new Error('token not registered');return f(this);}singleton<T>(t:Token<T>,factory:(c:Container)=>T):void{let instance:T|undefined;this.register(t,(c)=>{if(!instance)instance=factory(c);return instance;});}}

How it works

Count the class Container and the function token as the entire surface area of Dependency Injection Container Typed.

Instead of silently continuing, the code raises Error at the guard.

Putting it to use

token is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

How does the snippet fail?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `token` at load time.