Full answer
Dependency injection (DI) means a component receives what it needs instead of creating it. An inversion of control (IoC) container automates the wiring.
Core pieces:
- Registration:
register(token, factory, { lifetime }). A token can be a string, a symbol, or a class. A factory receives the container (or aresolvefunction) and returns an instance, so dependencies are declared by callingresolveinside the factory. JavaScript has no runtime types, so decorators or reflection metadata are needed for automatic constructor injection, while factories are simple and explicit. - Lifetimes:
singleton(one instance for the container),transient(a new instance for each resolve), andscoped(one instance per scope, such as one per request on a server). A singleton must not depend on a scoped service, or the scoped instance will be captured and outlive its scope. - Resolution path: keep a stack of tokens being resolved. If a token appears again, throw an error that shows the cycle (
A -> B -> A). Also throw a clear error for a missing registration with the path that led to it. - Child containers and scopes:
createScope()returns a container that shares registrations, owns its scoped cache, and delegates singletons to the parent. Overriding a registration in a child is how tests and special cases replace services. - Async factories and disposal: real systems need async creation and a
dispose()that closes resources in reverse order of creation. - Testing benefit: swap the real HTTP client for a fake with one registration, with no global mocks.
Trade-offs: containers add indirection, and hidden dependencies can make flows hard to follow. For small apps, passing parameters or using module-level singletons is simpler. Use a container when many components share services and need different lifetimes or test replacements.
function createContainer(parent = null) {
const registrations = new Map();
const scopedCache = new Map();
const singletonCache = new Map();
function find(token) {
if (registrations.has(token)) return { registration: registrations.get(token), owner: api };
return parent?.find(token);
}
function resolve(token, path = []) {
const found = find(token);
if (!found) throw new Error(`No registration for "${String(token)}"` + (path.length ? ` (needed by ${path.join(' -> ')})` : ''));
if (path.includes(token)) throw new Error(`Circular dependency: ${[...path, token].join(' -> ')}`);
const { factory, lifetime } = found.registration;
if (lifetime === 'singleton' && found.owner !== api) return found.owner.resolveFrom(token, path);
const next = [...path, token];
const inner = (dependency) => resolve(dependency, next);
if (lifetime === 'transient') return factory(inner);
const cache = lifetime === 'singleton' ? singletonCache : scopedCache;
if (!cache.has(token)) cache.set(token, factory(inner));
return cache.get(token);
}
const api = {
find,
resolveFrom: resolve,
register(token, factory, { lifetime = 'singleton' } = {}) {
registrations.set(token, { factory, lifetime });
return api;
},
resolve: (token) => resolve(token),
createScope: () => createContainer(api),
};
return api;
}
let loggerCount = 0;
let requestCount = 0;
const container = createContainer()
.register('config', () => ({ apiUrl: 'https://api.example.test' }))
.register('logger', () => ({ id: ++loggerCount, log: (m) => `[log ${loggerCount}] ${m}` }))
.register('http', (get) => ({ get: (path) => `GET ${get('config').apiUrl}${path}` }))
.register('requestContext', () => ({ id: ++requestCount }), { lifetime: 'scoped' })
.register('userService', (get) => ({ load: (id) => `${get('http').get('/users/' + id)} for request ${get('requestContext').id}` }), { lifetime: 'scoped' })
.register('transientId', () => ({ at: Symbol('instance') }), { lifetime: 'transient' });
console.log('singleton shared:', container.resolve('logger') === container.resolve('logger'), '| created:', loggerCount);
console.log('transient is new each time:', container.resolve('transientId') !== container.resolve('transientId'));
const scopeA = container.createScope();
const scopeB = container.createScope();
console.log(scopeA.resolve('userService').load(1));
console.log(scopeA.resolve('userService') === scopeA.resolve('userService'), '| same request id in a scope:', scopeA.resolve('requestContext').id);
console.log(scopeB.resolve('userService').load(2));
console.log('singleton shared across scopes:', scopeA.resolve('http') === scopeB.resolve('http'));
const testScope = container.createScope().register('http', () => ({ get: (path) => `FAKE ${path}` }));
console.log('override in a child:', testScope.resolve('http').get('/users/9'), '| parent still real:', container.resolve('http').get('/x'));
container.register('a', (get) => get('b')).register('b', (get) => get('c')).register('c', (get) => get('a'));
try { container.resolve('a'); } catch (error) { console.log(error.message); }
try { container.resolve('missing'); } catch (error) { console.log(error.message); }
container.register('needsMissing', (get) => get('database'));
try { container.resolve('needsMissing'); } catch (error) { console.log(error.message); }Run with Node.js v24.22.1 as js-197.js; two runs gave identical output. Output: singleton shared: true | created: 1 transient is new each time: true GET https://api.example.test/users/1 for request 1 true | same request id in a scope: 1 GET https://api.example.test/users/2 for request 2 singleton shared across scopes: true override in a child: FAKE /users/9 | parent still real: GET https://api.example.test/x Circular dependency: a -> b -> c -> a No registration for "missing" No registration for "database" (needed by needsMissing)
Key points
- Register tokens with factories; resolve inside factories to declare dependencies.
- Lifetimes: singleton, transient, and scoped; do not capture scoped services in singletons.
- Track the resolution stack to detect cycles and report missing tokens with a path.
- Child scopes share registrations but own scoped instances; overrides help tests.
- Consider async creation and disposal; avoid containers when plain parameters are enough.
Common mistakes
- Letting a singleton hold a scoped service.
- Missing cycle detection, which causes a stack overflow.
- Using a container as a global service locator everywhere.
- Hiding dependencies so that no one can see what a function needs.
Follow-ups
- How would you add async factories and disposal?
- How do decorators or metadata enable constructor injection?
- When would you skip a container entirely?
Tips
- Define dependency injection in one sentence before the code.
- Mention lifetimes and the captive dependency problem.
- Show how testing becomes simpler.