Build a Dependency Injection Container
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
Write a class Container. register(name, factory, options) adds a service and returns the container: factory is a function that receives the container and returns the service, so it can resolve whatever the service needs. options may be left out; with { singleton: true } the factory runs only on the first resolve, and every later resolve returns that same value, whatever it is. Otherwise each resolve calls the factory again. Nothing runs at register time. Registering a name again replaces it, forgetting any value made by the old factory. resolve(name) returns the service, and throws an Error with the message "Unknown service: name" for a name that isn't registered. When resolving a service needs that same service again, directly or through others, throw an Error "Circular dependency: " followed by every name being resolved, from the outermost resolve call to the repeat, joined by " -> ": "Circular dependency: a -> b -> a" when a needs b and b needs a. A factory's error passes on to the caller and the container keeps working: a singleton whose factory threw isn't saved, so the next resolve tries again.
Your code must pass
- Resolves a registered service, passing the container to its factory
- Calls the factory on every resolve unless it's a singleton
- Throws for an unknown service
- Registering again replaces the service
- Reports a circular dependency with its path
- Still works after a factory throws