Dependency Injection & IoC Container¶
Katal v3 features a Real Inversion of Control (IoC) Container inspired by Laravel and NestJS. It provides constructor autowiring, request-scoped child containers, typed injection tokens, strict parameter diagnostics, and deferred service providers.
1. Quick Start¶
import { Application, Controller } from "katal";
import type { RequestContext } from "katal";
// 1. Define a domain service
class PaymentService {
async processPayment(amount: number) {
return { transactionId: "tx_9981", status: "success" };
}
}
// 2. Define Controller with Constructor Injection
class CheckoutController extends Controller {
constructor(private readonly payments: PaymentService) {
super();
}
async handle(ctx: RequestContext) {
const result = await this.payments.processPayment(100);
return this.success(result);
}
}
// 3. Register service in container
const app = new Application({ port: 3000 });
app.singleton(PaymentService);
// 4. Register controller route - Katal autowires PaymentService into CheckoutController!
app.getRouter().post("/api/checkout", CheckoutController);
await app.listen();
2. Service Lifetimes¶
| Lifetime | Registration Method | Scope | When to Use |
|---|---|---|---|
| Singleton | app.singleton(token, factory?) |
Application | Database connection pools, Redis clients, configuration repositories, event buses. Created once on first resolve and shared globally. |
| Transient | app.bind(token, factory) |
Per-Resolution | Stateful worker tasks, file parsers, transient calculators. A brand new instance is instantiated every time resolve() is called. |
| Scoped | app.scoped(token, factory) |
Request / Scope | Tenant context, request telemetry counters, current authenticated user state. Shared within an individual HTTP request, isolated across concurrent requests. |
| Instance | app.instance(token, value) |
Application | Binding pre-instantiated external objects (e.g. third-party SDK client, raw configuration objects). |
Request-Scoped Services Example¶
class RequestAuditContext {
public readonly requestId = crypto.randomUUID();
public readonly timestamp = Date.now();
public user?: { id: string; role: string };
}
// Scoped instance: every HTTP request gets its own distinct, isolated instance
app.scoped(RequestAuditContext, () => new RequestAuditContext());
3. Injection Tokens¶
You can register and resolve services using:
1. Class Constructors: app.singleton(DatabaseService)
2. Typed Tokens: Type-safe interface bindings with createToken<T>()
3. Symbols: Symbol.for("IUserRepository")
4. String Aliases: "config", "cache", "auth"
Type-Safe Interface Tokens (TypedToken<T>)¶
Because TypeScript interfaces are erased at runtime, use Katal's createToken<T>() to bind interfaces with full static type checking:
import { createToken } from "katal";
// 1. Define interface
export interface IEmailSender {
send(to: string, subject: string, body: string): Promise<void>;
}
// 2. Create typed token
export const EmailSenderToken = createToken<IEmailSender>("IEmailSender");
// 3. Implement concrete service
export class SmtpEmailSender implements IEmailSender {
async send(to: string, subject: string, body: string) {
console.log(`Sending email to ${to}: ${subject}`);
}
}
// 4. Register binding
app.singleton(EmailSenderToken, () => new SmtpEmailSender());
// 5. Statically typed resolution: sender is typed as IEmailSender!
const sender = app.resolve(EmailSenderToken);
4. Parameter Autowiring & __paramTokens¶
When autowiring controllers or services whose constructor arguments are interfaces or tokenized dependencies, declare static __paramTokens on the class:
import { Controller } from "katal";
import type { RequestContext } from "katal";
import { EmailSenderToken, type IEmailSender } from "./tokens";
import { DatabaseService } from "./DatabaseService";
export class NotificationController extends Controller {
// Declare tokens matching constructor parameter order:
static __paramTokens = [EmailSenderToken, DatabaseService];
constructor(
private readonly email: IEmailSender,
private readonly db: DatabaseService
) {
super();
}
async handle(ctx: RequestContext) {
await this.email.send("admin@corp.com", "Alert", "Disk space low");
return this.success({ sent: true });
}
}
5. Strict Parameter Diagnostics¶
To prevent confusing runtime bugs where missing parameters evaluate to undefined, Katal's container performs strict compile-time and runtime arity validation:
- Arity Mismatch: If a class constructor expects 2 parameters but
__paramTokensonly provides 1, the container immediately throws an actionable diagnostic error:Error: Class "OrderController" constructor expects 2 parameters, but only 1 tokens were declared in __paramTokens. - Exact Parameter Index: When resolving dependencies recursively, if parameter index 1 fails, Katal pinpoints the exact parameter:
Error: Failed to resolve parameter #1 ("IEmailSender") for constructor of "NotificationController": Token not registered.
6. Hierarchical Child Scopes (createScope())¶
For background queues or event listeners, spawn child scopes to resolve request-scoped or isolated services:
const container = app.getContainer();
// Create isolated child scope
const childScope = container.createScope();
// Scoped instances resolved here are cached only in childScope
const auditCtx = childScope.resolve(RequestAuditContext);
// Teardown scope when work finishes
childScope.clear();
7. Deferred Service Providers¶
Katal v3 supports Deferred Providers that delay loading expensive dependencies (such as heavy database connection pools or external AI SDKs) until their DI token is explicitly requested:
import { ServiceProvider } from "katal";
export class HeavyAnalyticsProvider extends ServiceProvider {
override readonly isDeferred = true;
override readonly provides = ["analytics_engine"];
override register() {
this.container.singleton("analytics_engine", () => {
console.log("Analytics engine instantiated on-demand!");
return new AnalyticsEngine();
});
}
}
app.registerProvider(HeavyAnalyticsProvider);