Projects / DI container / Phase 2
Phase 2 of 4 · about 2.5 hours
A graph of services
You end with a container that wires a real five-service app, explains every failure with a full path, and lets tests swap parts out.
Step 2.1: Services that need services (about 50 minutes)
Factories already receive the container, so they can resolve their own dependencies. Let's wire a small app. Create src/try_graph.ts:
import { Container, Token } from './container.js';
class Config {
constructor(readonly dbUrl: string) {}
}
class Logger {
log(message: string) {
console.log(`[log] ${message}`);
}
}
class Database {
constructor(
readonly url: string,
readonly logger: Logger,
) {
logger.log(`connect ${url}`);
}
}
class UserRepo {
constructor(readonly db: Database) {}
}
class App {
constructor(
readonly users: UserRepo,
readonly logger: Logger,
) {}
}
const ConfigT = new Token<Config>('Config');
const LoggerT = new Token<Logger>('Logger');
const DatabaseT = new Token<Database>('Database');
const UserRepoT = new Token<UserRepo>('UserRepo');
const AppT = new Token<App>('App');
const container = new Container()
.singleton(ConfigT, () => new Config('postgres://localhost/app'))
.singleton(LoggerT, () => new Logger())
.singleton(DatabaseT, (c) => new Database(c.resolve(ConfigT).dbUrl, c.resolve(LoggerT)))
.singleton(UserRepoT, (c) => new UserRepo(c.resolve(DatabaseT)))
.singleton(AppT, (c) => new App(c.resolve(UserRepoT), c.resolve(LoggerT)));
const app = container.resolve(AppT);
console.log('one logger shared:', app.logger === app.users.db.logger);
The container builds the pieces on demand. Asking for App triggers UserRepo, which triggers Database, which triggers Config and Logger.
[log] connect postgres://localhost/app
one logger shared: true
The connect line printed once, and Logger is the same object everywhere it is used. Nobody wrote "create the logger first": the order fell out of who needs whom.
Step 2.2: Say exactly what went wrong (about 40 minutes)
Two mistakes will happen to everyone using a container: forgetting to register something, and building a loop (A needs B needs C needs A). A good container tells you where. We keep a list of the tokens currently being built, outermost first. Replace the resolve method and add the list:
resolve<T>(token: Token<T>): T {
if (this.#path.includes(token)) {
throw new Error(`Circular dependency: ${[...this.#path, token].join(' -> ')}`);
}
const registration = this.#registrations.get(token);
if (registration === undefined) {
const trail = [...this.#path, token].join(' -> ');
throw new Error(`Nothing is registered for ${token} (needed by: ${trail})`);
}
if (registration.lifetime === 'singleton' && this.#singletons.has(token)) {
return this.#singletons.get(token) as T;
}
this.#path.push(token);
try {
const value = registration.factory(this) as T;
if (registration.lifetime === 'singleton') this.#singletons.set(token, value);
return value;
} finally {
this.#path.pop();
}
}
}
Before building anything, resolve checks whether the token is already on the list. If it is, we have gone in a circle, and the list is the path. A missing token reports the same list. The try/finally pops the list even when a factory throws, so one failure does not poison later calls. Create src/try_errors.ts:
import { Container, Token } from './container.js';
const A = new Token<string>('A');
const B = new Token<string>('B');
const C = new Token<string>('C');
const Db = new Token<string>('Db');
const cycle = new Container()
.singleton(A, (c) => c.resolve(B))
.singleton(B, (c) => c.resolve(C))
.singleton(C, (c) => c.resolve(A));
try {
cycle.resolve(A);
} catch (e) {
console.log((e as Error).message);
}
const missing = new Container()
.singleton(A, (c) => c.resolve(B))
.singleton(B, (c) => c.resolve(Db));
try {
missing.resolve(A);
} catch (e) {
console.log((e as Error).message);
}
// the failed attempt must not poison the container: a later resolve still works
missing.singleton(Db, () => 'db');
console.log('after registering Db:', missing.resolve(A));
Circular dependency: Token(A) -> Token(B) -> Token(C) -> Token(A)
Nothing is registered for Token(Db) (needed by: Token(A) -> Token(B) -> Token(Db))
after registering Db: db
Both messages show the trail from the thing you asked for down to the thing that went wrong. The last line proves the container still works after two failures.
Step 2.3: Swap parts for tests (about 30 minutes)
Tests want a fake mailer, not a real one. Registering the same token again replaces it, and the container drops any cached singleton for it (see #add in the listing above). Create src/try_replace.ts:
import { Container, Token } from './container.js';
interface Mailer {
send(to: string): string;
}
const MailerT = new Token<Mailer>('Mailer');
const Signup = new Token<(email: string) => string>('Signup');
const container = new Container()
.singleton(MailerT, () => ({ send: (to) => `really sent mail to ${to}` }))
.singleton(Signup, (c) => (email) => c.resolve(MailerT).send(email));
console.log(container.resolve(Signup)('[email protected]'));
// In a test: swap the real mailer for a fake, then build again.
const sent: string[] = [];
container.singleton(MailerT, () => ({ send: (to) => (sent.push(to), 'fake') }));
container.singleton(Signup, (c) => (email) => c.resolve(MailerT).send(email));
console.log(container.resolve(Signup)('[email protected]'), sent);
really sent mail to [email protected]
fake [ '[email protected]' ]
Pitfall: replacement only helps things built after the swap. A singleton that already took the old mailer into its own fields keeps it. Do the replacing before the first resolve, usually in test setup.
Step 2.4: Where resolving belongs (about 30 minutes)
A factory that calls c.resolve(...) is convenient, but code that calls resolve all over the app is hiding its needs, which is the problem we set out to solve. A good rule: resolve at the edges (the main function, the start of each request), and pass the results into plain constructors and functions. Classes should say what they need in their constructor and never see the container. That is why our Database class takes a url and a logger, not a container.
Think it through: which of the classes in try_graph.ts import the container? None of them. Only the wiring does.
Phase 2 done
The container wires graphs, explains failures and supports test doubles. Next: per-request state.