Disposal
Factory providers can declare an onDispose hook for cached instances. Call
container.dispose() at the lifecycle boundary you own.
import { createContainer, createToken, provideFactory } from "di-craft";
class Connection { private closed = false;
query(): string { return this.closed ? "closed" : "open"; }
close(): void { this.closed = true; }}
const CONNECTION = createToken<Connection>("CONNECTION");
const container = createContainer([ provideFactory(CONNECTION, { useFactory: () => new Connection(), onDispose: (connection) => { connection.close(); }, }),]);
const connection = container.get(CONNECTION);
connection.query();
await container.dispose();- Hooks run in reverse creation order.
- Async hooks are awaited.
- Calling
dispose()more than once is safe. - A container disposes only cached instances it owns.
- Unresolved providers have nothing to dispose.
- Transient instances are not tracked and cannot declare
onDispose.
Child containers are disposed independently from their parents. In a request lifecycle, dispose the request child after the handler settles and keep the root container alive until application shutdown.
The Node.js adapter and explicit Next.js request runner handle
child-container disposal in finally blocks.