Resolve Typed Services from a DI Container
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Write a dependency injection container. Export a class Token<T>, made with new Token<T>(name), that stands for a service of type T, and a class Container. register(token, factory) stores a factory, a function that gets the container (so it can resolve other services) and returns the service; it returns the container for chaining. resolve(token) calls the factory the first time and returns that same instance every time after, and throws if nothing is registered for the token. Type it so resolve returns the token's T, a factory must return the token's type, and a Token<string> can't be used where a Token<number> is expected.
Your code must pass
- Resolves a registered service
- Makes each service once, when first resolved
- Throws for a token with nothing registered
- Has no type errors
- resolve returns the token's type
- Rejects a factory of the wrong type
- Tokens of different types don't mix