2020-09-01 20:04:48 +00:00
|
|
|
"""`Factory` provider delegation example."""
|
2015-07-20 15:46:45 +00:00
|
|
|
|
2020-09-01 01:26:21 +00:00
|
|
|
from typing import Callable, List
|
2016-06-08 13:54:47 +00:00
|
|
|
|
2020-09-03 20:46:03 +00:00
|
|
|
from dependency_injector import containers, providers
|
2015-07-20 15:46:45 +00:00
|
|
|
|
|
|
|
|
2020-01-26 23:41:36 +00:00
|
|
|
class User:
|
2020-09-01 01:26:21 +00:00
|
|
|
def __init__(self, uid: int) -> None:
|
|
|
|
self.uid = uid
|
2016-06-08 13:39:53 +00:00
|
|
|
|
|
|
|
|
2020-09-01 01:26:21 +00:00
|
|
|
class UserRepository:
|
|
|
|
def __init__(self, user_factory: Callable[..., User]) -> None:
|
|
|
|
self.user_factory = user_factory
|
2016-06-08 13:39:53 +00:00
|
|
|
|
2020-09-01 01:26:21 +00:00
|
|
|
def get_all(self) -> List[User]:
|
|
|
|
return [
|
|
|
|
self.user_factory(**user_data)
|
|
|
|
for user_data in [{'uid': 1}, {'uid': 2}]
|
|
|
|
]
|
2016-06-08 13:39:53 +00:00
|
|
|
|
2015-07-20 15:46:45 +00:00
|
|
|
|
2020-09-03 20:46:03 +00:00
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
|
|
|
user_factory = providers.Factory(User)
|
|
|
|
|
|
|
|
user_repository_factory = providers.Factory(
|
|
|
|
UserRepository,
|
|
|
|
user_factory=user_factory.provider,
|
|
|
|
)
|
2015-07-20 15:46:45 +00:00
|
|
|
|
2016-06-08 13:39:53 +00:00
|
|
|
|
2020-09-01 01:26:21 +00:00
|
|
|
if __name__ == '__main__':
|
2020-09-03 20:46:03 +00:00
|
|
|
container = Container()
|
|
|
|
|
|
|
|
user_repository = container.user_repository_factory()
|
2020-07-18 04:40:14 +00:00
|
|
|
|
2020-09-01 01:26:21 +00:00
|
|
|
user1, user2 = user_repository.get_all()
|
2017-10-13 17:15:21 +00:00
|
|
|
|
2020-09-01 01:26:21 +00:00
|
|
|
assert user1.uid == 1
|
|
|
|
assert user2.uid == 2
|