python-dependency-injector/examples/providers/factory_delegation.py

38 lines
821 B
Python
Raw Normal View History

"""`Factory` providers delegation example."""
2015-07-20 18:46:45 +03:00
from typing import Callable, List
from dependency_injector import providers
2015-07-20 18:46:45 +03:00
class User:
def __init__(self, uid: int) -> None:
self.uid = uid
2016-06-08 16:39:53 +03:00
class UserRepository:
def __init__(self, user_factory: Callable[..., User]) -> None:
self.user_factory = user_factory
2016-06-08 16:39:53 +03:00
def get_all(self) -> List[User]:
return [
self.user_factory(**user_data)
for user_data in [{'uid': 1}, {'uid': 2}]
]
2016-06-08 16:39:53 +03:00
2015-07-20 18:46:45 +03:00
user_factory = providers.Factory(User)
user_repository_factory = providers.Factory(
UserRepository,
user_factory=user_factory.provider,
)
2015-07-20 18:46:45 +03:00
2016-06-08 16:39:53 +03:00
if __name__ == '__main__':
user_repository = user_repository_factory()
user1, user2 = user_repository.get_all()
2017-10-13 20:15:21 +03:00
assert user1.uid == 1
assert user2.uid == 2