Inversion of Control
IoC containers, provider registration, and dependency resolution.
20 minLevel 16 of 20
IoC vs DI
Inversion of Control means the framework calls your code (Hollywood principle: don't call us, we'll call you). DI is the most common IoC technique for supplying dependencies.
Nest owns the application lifecycle and invokes your controllers.
Framework calls you
type Handler = () => string;
class MiniContainer {
private routes = new Map<string, Handler>();
get(path: string, handler: Handler) { this.routes.set(path, handler); }
handle(path: string) {
const h = this.routes.get(path);
if (!h) throw new Error("404");
return h(); // framework calls your handler
}
}
const app = new MiniContainer();
app.get("/health", () => "ok");
console.log(app.handle("/health"));Containers resolve graphs
An IoC container registers providers, then recursively constructs dependencies. Open the IoC Container simulator to step through registration → resolution.
Tiny container
type Factory = (c: Container) => unknown;
class Container {
private factories = new Map<string, Factory>();
private cache = new Map<string, unknown>();
register(token: string, factory: Factory) { this.factories.set(token, factory); }
resolve<T>(token: string): T {
if (this.cache.has(token)) return this.cache.get(token) as T;
const f = this.factories.get(token);
if (!f) throw new Error("missing " + token);
const value = f(this);
this.cache.set(token, value);
return value as T;
}
}
const c = new Container();
c.register("db", () => ({ query: () => ["row"] }));
c.register("repo", (c) => ({ db: c.resolve("db"), all() { return (this.db as { query: () => string[] }).query(); } }));
console.log((c.resolve("repo") as { all: () => string[] }).all());Scopes
Singleton (default in Nest), request, and transient scopes change how often instances are created — critical for request-scoped tenancy or stateful services.
Singleton cache
let created = 0;
class Service { constructor() { created++; } }
const a = new Service();
const b = a; // singleton-style reuse
console.log(created, a === b);Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice