Dependency Injection Container in JavaScript
Level 5590 keystrokes
Dependency injection containers manage object creation and dependencies for loose coupling.
JavaScript code
// Simple Dependency Injection Container1class Container {2 constructor() { // Map to store registered services3 this.services = new Map();4 }5 register(name, factory) { // Store factory function with null instance (lazy loading)6 this.services.set(name, { factory, instance: null });7 }8 get(name) { // Retrieve the service definition9 const service = this.services.get(name); // Throw if service not registered10 if (!service) throw new Error(`Service ${name} not found`); // Create instance on first access (singleton pattern)11 if (!service.instance) { // The factory receives the container, so it can get its own dependencies12 service.instance = service.factory(this);13 } // Return the singleton instance14 return service.instance;15 }16}17 // Create container instance18const container = new Container();// Register a config service19container.register("config", () => ({ env: "prod" }));// Register logger that depends on config20container.register("logger", (c) => ({ log: (msg) => console.log(`[${c.get("config").env}] ${msg}`) }));21 // Use the logger service22container.get("logger").log("Hello");Output
[prod] Hello
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 22)× 22.× 16"× 12{× 11}× 11;× 10=× 7,× 5`× 4