Projects / DI container / Phase 1
Phase 1 of 4 · about 2.5 hours
Tokens and lifetimes
You end with a container that builds things by token, shares singletons, and refuses mistakes at compile time.
A token is a typed label for something the container can build. A factory is the function that builds it. The container maps tokens to factories.
Step 1.1: A token that knows its type (about 30 minutes)
Why not use strings as keys? container.get('Port') can return anything, and a typo only fails when the code runs. A token fixes both: the type travels with the key. Create src/container.ts:
export class Token<T> {
// Never assigned: this field exists so TypeScript can tell Token<string> from Token<number>.
declare readonly type: T;
constructor(readonly name: string) {}
toString(): string {
return `Token(${this.name})`;
}
}
export type Factory<T> = (container: Container) => T;
export class Container {
#factories = new Map<Token<unknown>, Factory<unknown>>();
register<T>(token: Token<T>, factory: Factory<T>): this {
this.#factories.set(token, factory);
return this;
}
resolve<T>(token: Token<T>): T {
const factory = this.#factories.get(token);
if (factory === undefined) {
throw new Error(`Nothing is registered for ${token}`);
}
return factory(this) as T;
}
}
Read the pieces:
Token<T>has a field calledtypethat we never assign.declaretells TypeScript the field exists without emitting code for it. Its only job is to makeToken<string>andToken<number>different types. Without it, TypeScript sees two empty-looking classes and treats them as the same.registertakes aToken<T>and a factory that returnsT. The sameTappears in both, so the compiler checks they agree.resolvereturnsT. The oneas Tinside is the only cast in the library, and it is safe becauseregisteronly ever stored a factory of the matching type.- The
#fields are private at runtime, not just in the type system.
Try it. Create src/try_basic.ts:
import { Container, Token } from './container.js';
const Greeting = new Token<string>('Greeting');
const Port = new Token<number>('Port');
const container = new Container();
container.register(Greeting, () => 'hello');
container.register(Port, () => 8080);
const greeting = container.resolve(Greeting);
const port = container.resolve(Port);
console.log(greeting.toUpperCase(), port + 1);
try {
container.resolve(new Token<string>('Missing'));
} catch (error) {
console.log((error as Error).message);
}
HELLO 8081
Nothing is registered for Token(Missing)
greeting is a string and port is a number, with no annotations from us. The missing token fails with a message that names it.
Step 1.2: The compiler catches wiring mistakes (about 40 minutes)
The point of typed tokens is what you cannot do. Create src/try_types.ts. The @ts-expect-error comments say "the next line must be a compile error"; if it compiles fine, tsc itself complains:
import { Container, Token } from './container.js';
const Port = new Token<number>('Port');
const container = new Container();
// @ts-expect-error a string factory cannot be registered for a number token
container.register(Port, () => 'not a number');
// @ts-expect-error resolve returns a number, which has no toUpperCase
container.resolve(Port).toUpperCase();
console.log('both mistakes were caught by the compiler');
both mistakes were caught by the compiler
It compiled and ran, which means both mistakes were rejected as promised. Delete one of the comments and run npx tsc again: you will see the exact error the compiler would give you. This trick, tests that are compile errors, comes back in Phase 4.
Think it through: what would happen if Token had no type field? Try removing it. The @ts-expect-error lines stop being errors, and tsc reports "Unused '@ts-expect-error' directive".
Step 1.3: Share or rebuild (about 40 minutes)
So far every resolve runs the factory again. Sometimes that is right (a new request id each time) and sometimes it is wrong (one database connection pool for the whole app). A lifetime says which. We start with two:
- singleton: build once, give the same object every time,
- transient: build a fresh one every time.
Replace container.ts. register becomes two methods, and the container remembers singletons:
export class Token<T> {
// Never assigned: this field exists so TypeScript can tell Token<string> from Token<number>.
declare readonly type: T;
constructor(readonly name: string) {}
toString(): string {
return `Token(${this.name})`;
}
}
export type Factory<T> = (container: Container) => T;
export type Lifetime = 'singleton' | 'transient';
type Registration = { factory: Factory<unknown>; lifetime: Lifetime };
export class Container {
#registrations = new Map<Token<unknown>, Registration>();
#singletons = new Map<Token<unknown>, unknown>();
singleton<T>(token: Token<T>, factory: Factory<T>): this {
this.#registrations.set(token, { factory, lifetime: 'singleton' });
return this;
}
transient<T>(token: Token<T>, factory: Factory<T>): this {
this.#registrations.set(token, { factory, lifetime: 'transient' });
return this;
}
resolve<T>(token: Token<T>): T {
const registration = this.#registrations.get(token);
if (registration === undefined) {
throw new Error(`Nothing is registered for ${token}`);
}
if (registration.lifetime === 'transient') {
return registration.factory(this) as T;
}
if (!this.#singletons.has(token)) {
this.#singletons.set(token, registration.factory(this));
}
return this.#singletons.get(token) as T;
}
}
Create src/try_lifetimes.ts:
import { Container, Token } from './container.js';
let made = 0;
const Id = new Token<number>('Id');
const Pool = new Token<{ id: number }>('Pool');
const container = new Container();
container.transient(Id, () => ++made);
container.singleton(Pool, () => ({ id: ++made }));
console.log('transient:', container.resolve(Id), container.resolve(Id), container.resolve(Id));
const a = container.resolve(Pool);
const b = container.resolve(Pool);
console.log('singleton:', a.id, b.id, 'same object:', a === b);
console.log('factories ran:', made);
transient: 1 2 3
singleton: 4 4 same object: true
factories ran: 4
The transient values are 1, 2, 3 because the factory ran three times. The singleton factory ran once (it got number 4), so both reads show 4 and the objects are the same one. The factory counter ends at 4.
Step 1.4: When to pick which (about 40 minutes)
Choose a lifetime by asking one question: is it safe for two callers to hold the same object at the same time?
| Kind of thing | Lifetime | Why |
|---|---|---|
| Config, logger, connection pool | singleton | Safe to share, expensive to build |
| Request id, current user, per-request database transaction | scoped (Phase 3) | Must not leak between requests |
| Small values, counters, anything with its own mutable state | transient | Cheap to build, sharing would cause surprises |
Pitfall: a singleton that holds mutable per-user data is a bug waiting for two users to show up at once. Phase 3 adds a check for a related mistake.
Phase 1 done
You have typed tokens and two lifetimes. Next, things that depend on other things.