11. TypeScript: DI Container (Generics)
TypeScriptA manual implementation of the inversion-of-control pattern using generics.
class Container {
private services = new Map();
register(name: string, instance: T): void {
this.services.set(name, instance);
}
resolve(name: string): T {
const service = this.services.get(name);
if (!service) throw new Error(`Service not found: ${name}`);
return service as T;
}
}
When to use
Used in larger applications where dependencies between many services need managing without passing them around manually.
Common pitfalls
Registering a service under the wrong name (a typo in a string) only fails at runtime — consider typed keys instead of plain strings.