Autowire¶
Autowire is light & simple dependency injection library for Python.
You can use dependency injection & resource management without any classes and any magics.
Since python already support nice context manager (PEP343), we don’t have to any extra interfaces for setting-up & tearing-down resource.
This is how to define resources in Autowire.
from autowire import Resource
from contextlib import contextmanager
# Define resources
db_connection_factory = Resource('db_connection_factory', __name__)
db_connection = Resource('db_connection', __name__)
# Implement db_connection resource
@db_connection.autowire(db_connection_factory)
@contextmanager
def with_db_connection(db_connection_factory):
conn = db_connection_factory()
try:
yield conn
except:
conn.rollback()
finally:
conn.close()
This is how to resolve resource implementations.
from autowire import Context
context = Context()
with context.resolve(db_connection) as conn:
conn.execute('SELECT * FROM ...')
...