Projects / DI container / Phase 3
Phase 3 of 4 · about 2.5 hours
Scopes and cleanup
You end with request scopes that share singletons but not scoped services, a guard against a classic lifetime bug, and orderly shutdown.
Step 3.1: Child containers (about 35 minutes)
A web server handles many requests at once. Some objects belong to one request (the request id, the current user) while others belong to the whole app. A scope is a child container for one request. It can see everything its parent registered, and it keeps its own cache for scoped services. Look at the new parts of container.ts:
constructor(readonly name: string) {}
toString(): string {
return `Token(${this.name})`;
}
}
export type Factory<T> = (container: Container) => T;
export type Lifetime = 'singleton' | 'scoped' | 'transient';
type Registration = { factory: Factory<unknown>; lifetime: Lifetime };
export class Container {
#registrations = new Map<Token<unknown>, Registration>();
#cache = new Map<Token<unknown>, unknown>();
#disposables: { dispose(): void }[] = [];
#parent: Container | undefined;
#root: Container;
#path: Token<unknown>[] = []; // only the root's list is used, so scopes share one trail
constructor(parent?: Container) {
this.#parent = parent;
this.#root = parent === undefined ? this : parent.#root;
}
createScope(): Container {
return new Container(this);
}
has(token: Token<unknown>): boolean {
return this.#find(token) !== undefined;
}
The constructor remembers the parent and finds the root, the top container. createScope makes a child. has walks up the chain with #find, which looks in this container and then in the parent, returning both the registration and its owner, the container that registered it.
Step 3.2: Scoped services (about 55 minutes)
Now a third lifetime, scoped: built once per scope. The rule for where an object lives:
| Lifetime | Lives in | Why |
|---|---|---|
| singleton | the container that registered it | shared by every scope |
| scoped | the scope that asked | one per request |
| transient | nowhere | built on every request |
Here is the whole resolve method that implements it:
resolve<T>(token: Token<T>): T {
const path = this.#root.#path;
if (path.includes(token)) {
throw new Error(`Circular dependency: ${[...path, token].join(' -> ')}`);
}
const found = this.#find(token);
if (found === undefined) {
throw new Error(`Nothing is registered for ${token} (needed by: ${[...path, token].join(' -> ')})`);
}
const { registration, owner } = found;
if (registration.lifetime === 'scoped' && this === this.#root) {
throw new Error(
`${token} is scoped, so it needs a scope (path: ${[...path, token].join(' -> ')}). ` +
'A singleton cannot use a scoped service: it would keep one request\'s object forever.',
);
}
if (registration.lifetime === 'transient') {
return this.#build(token, registration, this) as T;
}
// A singleton lives in the container that registered it, a scoped service in the scope asking.
const home = registration.lifetime === 'singleton' ? owner : this;
if (!home.#cache.has(token)) {
home.#cache.set(token, this.#build(token, registration, home, true));
}
return home.#cache.get(token) as T;
}
Walk through it:
- The cycle and missing checks are as before, but the path list lives on the root so that scopes share one trail.
homeis where the object is cached: the owner for singletons,thisfor scoped.- A singleton factory is called with its owner, not with the scope that asked. That is deliberate. A singleton must not be able to reach the request's scoped services.
Create src/try_scope.ts:
import { Container, Token } from './container.js';
let requests = 0;
const Logger = new Token<{ id: number }>('Logger');
const RequestId = new Token<number>('RequestId');
const Handler = new Token<string>('Handler');
const root = new Container()
.singleton(Logger, () => ({ id: 1 }))
.scoped(RequestId, () => ++requests)
.transient(
Handler,
(c) => `request ${c.resolve(RequestId)} using logger ${c.resolve(Logger).id}`,
);
const first = root.createScope();
const second = root.createScope();
console.log(first.resolve(Handler), '|', first.resolve(Handler));
console.log(second.resolve(Handler));
console.log('one request id per scope:', first.resolve(RequestId) === first.resolve(RequestId));
console.log('one logger for all:', first.resolve(Logger) === second.resolve(Logger));
request 1 using logger 1 | request 1 using logger 1
request 2 using logger 1
one request id per scope: true
one logger for all: true
Each scope has its own request id, and a transient Handler built twice in the first scope shows the same id both times. The logger is one object for everybody.
Step 3.3: The captive dependency (about 30 minutes)
Here is a bug that is easy to write. A singleton depends on a scoped service. The singleton is built during the first request, so it keeps that request's object forever, and every later request sees stale data. This is called a captive dependency. We already block it, because a singleton factory runs against the root, and the root refuses to build scoped services. Create src/try_captive.ts:
import { Container, Token } from './container.js';
const RequestId = new Token<number>('RequestId');
const Cache = new Token<string>('Cache');
const root = new Container()
.scoped(RequestId, () => 42)
.singleton(Cache, (c) => `cached for request ${c.resolve(RequestId)}`);
try {
root.createScope().resolve(Cache);
} catch (error) {
console.log((error as Error).message);
}
Token(RequestId) is scoped, so it needs a scope (path: Token(Cache) -> Token(RequestId)). A singleton cannot use a scoped service: it would keep one request's object forever.
The message names the path (Cache -> RequestId) and says why this is wrong. A bug that would show up as "sometimes users see each other's data" shows up as an error the first time the code runs.
Step 3.4: Clean up after yourself (about 30 minutes)
Some objects hold resources: connections, files, timers. When the request ends, its connection should close. When the app shuts down, the pool should close after every connection that used it. So: whatever is created first is closed last. Our dispose method walks the cached services that have a dispose method in reverse creation order, and collects errors so one failing cleanup does not stop the others:
dispose(): void {
const errors: unknown[] = [];
for (const item of this.#disposables.reverse()) {
try {
item.dispose();
} catch (error) {
errors.push(error);
}
}
this.#disposables = [];
this.#cache.clear();
if (errors.length > 0) throw new AggregateError(errors, 'Some services failed to dispose');
}
Create src/try_dispose.ts:
import { Container, Token } from './container.js';
const make = (name: string) => ({ dispose: () => console.log(`closed ${name}`) });
const Pool = new Token<{ dispose(): void }>('Pool');
const Conn = new Token<{ dispose(): void }>('Conn');
const root = new Container()
.singleton(Pool, () => make('pool'))
.scoped(Conn, (c) => (c.resolve(Pool), make('connection')));
const scope = root.createScope();
scope.resolve(Conn);
console.log('request ends');
scope.dispose();
console.log('app shuts down');
root.dispose();
request ends
closed connection
app shuts down
closed pool
The scope closed its connection when the request ended. The root closed the pool at shutdown, after the connection. Transient objects are not tracked: whoever asked for one owns it. That is a real design choice; some libraries track everything and hold memory until the scope ends.
Phase 3 done
Lifetimes, scopes and cleanup work. Last, make the API pleasant and the project shippable.