Skip to content

Add resource lifecycle management for scoped containers #2

@danielstarman

Description

@danielstarman

Summary

Support cleanup/teardown of resources when a scoped container exits, so that dependencies like database connections and client sessions are properly closed.

Motivation

Currently, Container.scope() creates child containers that know how to create dependencies but not how to clean them up. When a scope ends, any resources it created (DB connections, file handles, HTTP sessions) are leaked. For long-running applications, this is a real problem.

Proposed approach

  • Make scoped containers work as context managers (with parent.scope() as child:)
  • Support generator-based factories that yield the resource, with cleanup code after the yield
  • On scope exit, run teardown in reverse creation order
  • Both sync (with) and async (async with) context managers

Example:

def create_db():
    db = Database()
    db.connect()
    yield db
    db.close()

container.bind(Database, factory=create_db, singleton=True)

with container.scope() as child:
    db = child.resolve(Database)
    # ... use db ...
# db.close() called automatically

Non-goals

  • This should not affect transient bindings (no tracking of every transient instance)
  • This should not change existing behavior for non-generator factories

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions