Dependency injection and application context

Resolve shared resources through app, read request state through ctx, and register a lazy capability.

Read the caller and request input from ctx. Resolve database or queue dependencies through ctx.app. Shared capabilities initialize lazily per app instance. Request state stays with the request.

Get dependencies from the application

A controller receives the current request as ctx. Query parameters, the body, the principal, and the cancellation signal belong to that request. Obtain database, cache, configuration, and queue capabilities through ctx.app. Business code uses the interface, and Platform selects the driver.

const cache = await ctx.app.cache();
const value = await cache.get(key);
return ctx.json(value);

Scheduled tasks and other application code use the app they receive. When an operation needs an actor, read the principal in the controller and pass the identity the use case needs.

Register a capability when it needs an application lifecycle

Check the existing capabilities first. For a dependency shared across features and managed by the application, declare a factory with defineCapability. Register it in packages/service/app/capabilities.ts and expose the same method contract in AppCapabilityMethods. Factories can resolve other capabilities, and circular dependencies fail.

The first call initializes the factory. Concurrent callers share that result, successful instances are reused, and a later call can retry a failed initialization. Check first use, concurrent use, and retry after failure. Verify that principals and request input stay scoped to the original request. Database and ORM · Runtime