6.10 Stateful collaborators are built at the composition root and passed in: examples
Rule: ยง6.10 in the code standards.
Why
A function that receives its collaborators as parameters shows in its signature what it needs, and the composition root becomes the one place where the whole object graph is visible. A module that builds its own channel, client or watcher hides that dependency, and a second copy of the same state can drift from the first without anyone noticing.
A stateful collaborator is anything that holds I/O or state: a channel, a client, a watcher, a pipeline.
Who may build one:
- the composition root,
src/index.ts(B7), and itssrc/startup/collaborators; - the one orchestrator that alone uses the collaborator.
createBridge(src/transport/bridge.ts) builds its channels and its runtime connection, which nothing else uses.
Everything else receives the collaborator as a parameter or a factory argument.
Good: the root builds, the factory receives
src/index.ts:89 passes the server and bridge it built to the extension subsystem:
const extensions = createExtensionManager({ server, bridge, getReadOnly: isReadOnly });
src/transport/bridge.ts:281 builds a collaborator that only the bridge uses:
const runtime = createRuntimeConnection({ projectPath, explicitRuntimePort: opts?.explicitRuntimePort });
Bad: a client built on first use
src/lsp/lspSession.ts:44-50 is an existing case, listed in B7:
/** Singleton LSP client (lazy, shared across all LSP tool calls). */
let lspClient: LspClient | undefined = undefined;
function getLspClient(projectPath: string): LspClient {
if (!lspClient) lspClient = new LspClient(projectPath);
return lspClient;
}
Nothing in the signatures of the LSP tool handlers says they hold a socket. A test that wants a different client has no way to supply one.
Source
- Mark Seemann, Composition Root and Pure DI: compose the graph in one place near the entry point, without a container.
- Martin Fowler, Inversion of Control Containers and the Dependency Injection pattern: keep the configuration of services separate from their use.