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];
}
};
}
```