Resources (cleanup)

When a dependency needs cleanup (close/dispose/release), register it as a scoped service using a generator factory. If you omit a scope, the generator is attached to the initial app scope and cleaned up when you call container.close() or container.aclose().

Sync cleanup (generator)

See Scopes & cleanup.

Async cleanup (async generator)

See Async.

Important

Always put cleanup in a finally block. Code after yield is not guaranteed to run because closing a generator raises GeneratorExit at the yield point.

For a background job, keep the async scope inside the task. Cancel the task once and await it so the scope can finish async cleanup before cancellation reaches the caller. See Async for a runnable job example and its shutdown limits.