Explorer
Node.js

Implement a simple DI container with `register(name, factory)` and `resolve(name)` methods. Factories can depend on other services.

Problem Statement

Implement a simple DI container with `register(name, factory)` and `resolve(name)` methods. Factories can depend on other services.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Store factories in a registry keyed by name. šŸ’” Hint 2: resolve() calls the factory, passing the container so it can resolve its dependencies. šŸ’” Hint 3: Cache instances for singleton behavior. āœ… Solution: ```javascript function createContainer() { const factories = {}; const instances = {}; return { register(name, factory) { factories[name] = factory; }, resolve(name) { if (instances[name]) return instances[name]; if (!factories[name]) throw new Error(`Service ${name} not found`); instances[name] = factories[name](this); return instances[name]; } }; } ```

Dependency Injection Container

Hard
Implement a simple DI container with `register(name, factory)` and `resolve(name)` methods. Factories can depend on other services.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"url":"postgres://localhost","connected":true}