dn-ioc

08 · Core Kernel

Lifecycle & Cleanup

A successful app.start() never stops the app on its own—you decide whether app.stop() is needed at all. A quick CLI script or a page-wide browser graph that dies when the tab closes doesn't need stop(), because the OS or tab reclaims everything anyway. Reach for onDispose() and app.stop() whenever something outlives the graph: a long-running server holding ports or DB pools, an isolated test case, or a UI widget that unmounts while the page lives on.

dispose.ts
1export const storeRef = provide(() => ({ closed: false }))23export const serviceRef = provide(({ inject, onDispose }) => {4  const store = inject(storeRef)5  onDispose(async () => {6    store.closed = true7  })8  return {9    read: () => inject(storeRef).closed,10  }11})1213export let service!: { read: () => boolean }1415export const disposeApp = bootstrapApp(({ inject }) => {16  service = inject(serviceRef)17})1819await disposeApp.start()20console.log(service.read()) // false (deferred inject works while running)21await disposeApp.stop()22// service.read() -> throws "Cannot inject after the app has stopped"

Closing Injection & LIFO Teardown

Calling app.stop() does two things in strict order:

  1. Closes inject() synchronously across the whole app: Before a single microtask runs, every inject() handle in the app is permanently shut. Any later inject() call—even for an already-cached instance or inside a private subtree, like service.read() above—immediately throws Cannot inject after the app has stopped.
  2. Runs onDispose hooks newest-first (LIFO): Hooks run one after another in reverse registration order. If your database pool registers first and your HTTP server registers second, stop() closes the HTTP server before draining the database pool.

Because inject() is already closed by the time cleanup hooks run, always capture dependencies into local variables before registering onDispose()—just like const store = inject(storeRef) in dispose.ts.

Repeated or concurrent app.stop() calls are idempotent: they return the exact same Promise and run each hook once. Once an app has stopped, calling app.start() again rejects with Cannot start an app that has been stopped.

Automatic Teardown with await using

Every App implements AsyncDisposable—defining [Symbol.asyncDispose] when native Symbol.asyncDispose exists, and falling back to [Symbol.for('Symbol.asyncDispose')] on older runtimes without the native symbol so TypeScript 5.2+'s downlevel await using emit still finds it.

In tests, CLI jobs, or request-scoped workers like runScopedTask(), await using app = bootstrapApp(...) guarantees app.stop() is awaited automatically when the block exits—even if code inside the block throws an error.

await-using.ts
1export const workerRef = provide(({ onDispose }) => {2  let stopped = false3  onDispose(async () => {4    stopped = true5  })6  return {7    get isStopped() {8      return stopped9    },10  }11})1213export const startWorker = ({ inject }: Context) => {14  inject(workerRef)15}1617export const runScopedTask = async () => {18  await using app = bootstrapApp(startWorker)19  await app.start()20} // app.stop() runs automatically here, even on throw

Wiring Shutdown Across Runtimes

Shutdown signals have no common denominator across JavaScript runtimes, so the kernel never attaches hidden global listeners. Wire app.stop() to whichever lifecycle trigger fits your platform:

RuntimeTriggerAsync cleanup
Node.js, Bunprocess.on('SIGINT' | 'SIGTERM', handler)Awaited, if the handler keeps the process alive
Browser sub-appYour own unmount call (React useEffect, Vue onScopeDispose, router leave)Awaited
Browser pageaddEventListener('pagehide', handler)Not reliable — keep hooks synchronous
Web WorkerA message from the host before worker.terminate()Only if the host waits before terminating
Serverless, edgeEnd of the request or invocation you scoped the app toDepends on the platform's keep-alive API

A few practical details to watch for in each environment:

  • Node.js & Bun (node-server.ts): Register SIGINT / SIGTERM listeners before await app.start(). Because bootstrapApp() doesn't run any provider yet, app already exists before port 3000 opens.
  • Browser widgets (browser-unmount.ts): Whenever possible, scope browser graphs to a component or route you unmount yourself (await ready; await app.stop()), where async cleanup hooks are properly awaited while the page stays open.
  • Browser tab unload (browser-pagehide.ts): Prefer pagehide over beforeunload (which breaks or gets skipped by the back/forward cache). Even with pagehide, browsers routinely discard the page before an async Promise settles—so keep unload hooks strictly synchronous, like navigator.sendBeacon().
node-server.ts
1import { createServer } from 'node:http'2import { bootstrapApp, provide } from 'dn-ioc'34export const serverRef = provide(({ onDispose }) => {5  const server = createServer().listen(3000)6  onDispose(() => new Promise<void>(resolve => server.close(() => resolve())))7  return server8})910export const app = bootstrapApp(({ inject }) => {11  inject(serverRef)12})1314// Register signal listeners before start() — bootstrapApp() runs nothing yet15for (const signal of ['SIGINT', 'SIGTERM'] as const) {16  process.on(signal, () => void app.stop())17}1819await app.start()
browser-unmount.ts
1export const socketRef = provide(({ onDispose }) => {2  const socket = new WebSocket('wss://example.com/live')3  onDispose(() => {4    socket.close()5  })6  return socket7})89export const mountLiveWidget = () => {10  const app = bootstrapApp(({ inject }) => {11    inject(socketRef)12  })13  const ready = app.start()1415  // Call from React useEffect cleanup, Vue onScopeDispose, or router leave hook16  return async () => {17    await ready18    await app.stop()19  }20}
browser-pagehide.ts
1export const sessionRef = provide(({ onDispose }) => {2  const sessionId = crypto.randomUUID()3  // Keep unload hooks synchronous — browsers may discard async work on unload4  onDispose(() => {5    navigator.sendBeacon('/session/end', sessionId)6  })7  return sessionId8})910export const pageApp = bootstrapApp(({ inject }) => {11  inject(sessionRef)12})1314addEventListener('pagehide', () => void pageApp.stop())1516await pageApp.start()

Hook Rules, Startup Rollback & Limits

Keep these invariants in mind when writing onDispose hooks:

  • Registration window: You can only call onDispose() while its own factory is actively running, and before stop() is called. A sync factory closes that window the moment it returns or throws; an async factory closes it when its returned Promise settles. Calling onDispose() after the factory finishes throws onDispose can only be called while the factory is running; calling it after shutdown starts throws Cannot register cleanup after the app has stopped.
  • Return void or Promise<void>: A cleanup hook must return void or Promise<void>—returning any other value (or a Promise resolving to a non-void value) is a TypeScript compile error, so accidental return values don't slip through unnoticed. Wrap non-void teardown calls (like Node's http.Server.close(), which returns the Server) in braces: onDispose(() => { server.close() }).
  • Never await app.stop() inside a hook: A cleanup hook is part of stop()'s own completion—awaiting app.stop() inside onDispose() will deadlock forever.
  • Hook errors & AggregateError: If one hook throws or rejects, stop() still executes all remaining hooks. A single failure is rethrown unchanged; multiple failures are combined into an AggregateError (App stop failed).
  • Automatic rollback on start() failure: If app.start() fails partway through booting, it automatically calls stop() to clean up resources registered so far before rejecting. One error is rethrown unchanged; if startup and cleanup both fail, start() rejects with an AggregateError (App startup and stop failed). Once start() succeeds, later runtime errors in your app do not automatically stop the graph.