python-dependency-injector/examples/containers/declarative_injections.py

43 lines
972 B
Python
Raw Normal View History

2020-08-14 20:27:17 +00:00
"""Declarative container injections example."""
2016-05-29 19:06:02 +00:00
import sqlite3
2020-08-14 20:27:17 +00:00
from dependency_injector import containers, providers
2016-05-29 19:06:02 +00:00
2020-08-14 20:27:17 +00:00
class UserService:
def __init__(self, db: sqlite3.Connection):
self.db = db
2016-05-29 19:06:02 +00:00
2020-08-14 20:27:17 +00:00
class AuthService:
def __init__(self, db: sqlite3.Connection, user_service: UserService):
self.db = db
self.user_service = user_service
class Container(containers.DeclarativeContainer):
2016-05-29 19:06:02 +00:00
database = providers.Singleton(sqlite3.connect, ':memory:')
2020-08-14 20:27:17 +00:00
user_service = providers.Factory(
UserService,
db=database,
)
auth_service = providers.Factory(
AuthService,
db=database,
user_service=user_service,
)
2016-05-29 19:06:02 +00:00
if __name__ == '__main__':
container = Container()
2016-05-29 19:06:02 +00:00
user_service = container.user_service()
auth_service = container.auth_service()
2016-05-29 19:06:02 +00:00
assert user_service.db is auth_service.db is container.database()
assert isinstance(auth_service.user_service, UserService)