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
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
with parent.scope() as child:)yieldthe resource, with cleanup code after the yieldwith) and async (async with) context managersExample:
Non-goals