Dependency Injection Container Typed
Implement a typed DI container with token-based registration and resolution for testable service wiring.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.