@@ -35,15 +35,16 @@ Here's a quick example to get you started:
35
35
``` python
36
36
from dependency_injection.container import DependencyContainer
37
37
38
- # Define dependency abstraction
38
+ # Define an abstract Connection
39
39
class Connection :
40
40
pass
41
41
42
- # Define dependency implementations
42
+ # Define a specific implementation of the Connection
43
43
class PostgresConnection (Connection ):
44
44
def connect (self ):
45
45
print (" Connecting to PostgreSQL database..." )
46
46
47
+ # Define a repository that depends on some type of Connection
47
48
class UserRepository :
48
49
def __init__ (self , connection : Connection):
49
50
self ._connection = connection
@@ -52,17 +53,19 @@ class UserRepository:
52
53
self ._connection.connect()
53
54
print (" Fetching users from the database..." )
54
55
55
- # Get a dependency container
56
+ # Get an instance of the (default) DependencyContainer
56
57
container = DependencyContainer.get_instance()
57
58
58
- # Register dependencies
59
+ # Register the specific connection type as a singleton instance
59
60
container.register_singleton(Connection, PostgresConnection)
61
+
62
+ # Register UserRepository as a transient (new instance every time)
60
63
container.register_transient(UserRepository)
61
64
62
- # Resolve dependencies
65
+ # Resolve an instance of UserRepository, automatically injecting the required Connection
63
66
user_repository = container.resolve(UserRepository)
64
67
65
- # Use the dependencies
68
+ # Use the resolved user_repository to perform an operation
66
69
user_repository.find_all()
67
70
```
68
71
0 commit comments