DI Bag API / index / FactoryContext
Interface: FactoryContext
Defined in: acquisition-context.ts:46
Cooperative cancellation and acquisition-local ownership supplied to a context-aware factory.
See
https://dany-fedorov.github.io/di-bag/guides/tutorial.html#make-selected-services-ready
Properties
abortSignal
ts
readonly abortSignal: AbortSignal;Defined in: acquisition-context.ts:60
Return the signal that aborts when the acquisition's owning container begins closing.
Example
ts
declare function fetchCatalog(signal: AbortSignal): Promise<string[]>;
const catalog = DiBag.createProvider(async (_dependencies: {}, factoryContext) => fetchCatalog(factoryContext.abortSignal), {
factoryReceivesContext: true, factoryReturnKind: 'native-promise',
});
const container = DiBag.createBuilder().withServices({ catalog }).buildContainer();
const names: Promise<string[]> = container.resolve('catalog'); // close() aborts the signal while fetchCatalog is pending
await container.close();Methods
pushDisposer()
ts
pushDisposer(this: void, disposer: (this: void, disposerContext: DisposerContext) => void | Promise<void>): void;Defined in: acquisition-context.ts:81
Attach a disposer for a resource acquired during this factory call; pushed disposers run once in reverse order. Pass the release callback itself, such as () => socket.close(), rather than calling it here.
Parameters
| Parameter | Description |
|---|---|
this | - |
disposer | Releases the acquired resource when the factory fails or the container closes. |
Throws
DI_BAG_DISPOSER_PUSHED_AFTER_FACTORY when called after the factory settled.
Example
ts
declare function openLock(name: string): Promise<{ release(): Promise<void> }>;
declare function verify(name: string): Promise<void>;
const worker = DiBag.createProvider(async ({ name }: { name: string }, factoryContext) => {
const lock = await openLock(name);
factoryContext.pushDisposer(() => lock.release()); // released at close(), or at once if verify() rejects
await verify(name);
return { name };
}, { factoryReceivesContext: true });
const container = DiBag.createBuilder().withServices({ name: () => 'nightly', worker }).buildContainer();
const started: Promise<{ name: string }> = container.resolve('worker');
await container.close(); // runs lock.release() after the worker settled