@setu-ts/di-plugin — constructor injection and service scopes
Add it: setu add di adds it; add DiPlugin() to setu.config.ts yourself. It provides
CAPABILITIES.DI_CONTAINER (IContainer).
Register dependencies and resolve a scoped service per request
import { CAPABILITIES, createToken } from '@setu-ts/common';
import type { IContainer, IRequestContext } from '@setu-ts/common';
class Greeting {
constructor(readonly text: string) {}
}
const GREETING = createToken<Greeting>('greeting');
// In a plugin's register(); the container closes after bootstrap.
const container = ctx.services.get<IContainer>(CAPABILITIES.DI_CONTAINER);
container.register('greeting-text', { useValue: 'hello' });
container.register(GREETING, { useClass: Greeting, inject: ['greeting-text'] }, { scope: 'scoped' });
// One Greeting per request, disposed when it finishes.
function greet(request: IRequestContext): Greeting {
return container.forRequest(request).resolve(GREETING);
}
Behaviour the types do not show
defaultScopedefaults to'singleton';'transient'creates a new instance on every resolve.- The graph is validated at boot: a missing dependency, a cycle, or a singleton reaching a scoped
service (directly or through transients) fails
app.start()withContainerValidationError. - Resolving a
'scoped'token on the root container throwsScopeRequiredError; useforRequestorcreateScope. registerafter the container closes throwsContainerClosedError. A scope may register new tokens but not shadow one its parent has.autoRegisterdefaults totrue: unknown tokens fall back to the service registry, cached as singletons.useFactoryreceives itsinjectdependencies as arguments; a factory withoutinjectis not checked at boot.forRequestneeds the kernel’s request context; test request scopes withcreateTestApp.
Other options
DiPlugin({ autoRegister: false })disables fallback to framework capabilities.- A token is a string, a
createTokentoken, or a class;injectentries may be{ token, optional: true }. register’s third argument takesscopeanddispose;disposereleases what the container created.createContainerbuilds a standalone container, defaults automatic registration tofalse, and stays open untilcloseon theDiContainer.