Projects / DI container
TypeScript · about 10 hours · 4 phases
Build a dependency injection container in TypeScript
A service needs a database, the database needs a config, and the config needs the environment. Wire that up by hand in every file and you get a tangle: tests cannot swap a real mailer for a fake, and changing one constructor means editing ten call sites. A dependency injection container keeps the wiring in one place. You say how to build each thing once, and the container builds them in the right order, shares what should be shared and complains clearly when something is missing. In about 10 hours you will build a small one with explicit tokens (no decorators, no magic), tested and packaged like a real library.
You work in four phases of about 2.5 hours each, and every phase ends with something you can run. By the end you will have:
- tokens that carry a type, so the compiler knows what
resolvereturns, - singleton, scoped and transient lifetimes, with a request scope that cleans up after itself,
- errors that name the full path ("A needs B needs C, and C is missing"), and cycle detection,
- a typed way to list dependencies that the compiler checks, plus tests and a package you install from another folder.
You need basic TypeScript (types, classes, generics at the level of Array<string>) and Node.js. Anything more is explained when it first appears.
If generics look unfamiliar, read the generics page of the TypeScript handbook first.
The four phases
Tokens and lifetimes
You end with a container that builds things by token, shares singletons, and refuses mistakes at compile time.
- 1.1 A token that knows its type30 min
- 1.2 The compiler catches wiring mistakes40 min
- 1.3 Share or rebuild40 min
- 1.4 When to pick which40 min
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.
- 2.1 Services that need services50 min
- 2.2 Say exactly what went wrong40 min
- 2.3 Swap parts for tests30 min
- 2.4 Where resolving belongs30 min
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.
- 3.1 Child containers35 min
- 3.2 Scoped services55 min
- 3.3 The captive dependency30 min
- 3.4 Clean up after yourself30 min
A typed API, tests and a package
You end with a typed way to list dependencies, tests that include compile errors, and a package you install from another folder.
- 4.1 Say what you need, once30 min
- 4.2 Tests that are compile errors40 min
- 4.3 Runtime tests40 min
- 4.4 Package it and measure it40 min