-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
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
yieldthe 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 automaticallyNon-goals
- This should not affect transient bindings (no tracking of every transient instance)
- This should not change existing behavior for non-generator factories
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels