-
-
Notifications
You must be signed in to change notification settings - Fork 321
/
Copy pathdependency.py
45 lines (27 loc) · 1.01 KB
/
dependency.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""`Dependency` provider example."""
import abc
import dataclasses
from dependency_injector import containers, providers
class DbAdapter(metaclass=abc.ABCMeta):
...
class SqliteDbAdapter(DbAdapter):
...
class PostgresDbAdapter(DbAdapter):
...
@dataclasses.dataclass
class UserService:
database: DbAdapter
class Container(containers.DeclarativeContainer):
database = providers.Dependency(instance_of=DbAdapter)
user_service = providers.Factory(
UserService,
database=database,
)
if __name__ == "__main__":
container1 = Container(database=providers.Singleton(SqliteDbAdapter))
container2 = Container(database=providers.Singleton(PostgresDbAdapter))
assert isinstance(container1.user_service().database, SqliteDbAdapter)
assert isinstance(container2.user_service().database, PostgresDbAdapter)
container3 = Container(database=providers.Singleton(object))
container3.user_service() # <-- raises error:
# <object ...> is not an instance of DbAdapter