0
# Dependency Injector
1
2
A comprehensive dependency injection framework for Python that enables developers to implement the dependency injection principle effectively. It provides various provider types for dependency assembly, supports provider overriding for testing, reads configuration from multiple sources, offers resource management capabilities, and includes framework integration through dependency wiring.
3
4
## Package Information
5
6
- **Package Name**: dependency-injector
7
- **Language**: Python
8
- **Installation**: `pip install dependency-injector`
9
10
## Core Imports
11
12
```python
13
from dependency_injector import containers, providers
14
```
15
16
Common for dependency wiring:
17
18
```python
19
from dependency_injector.wiring import Provide, inject
20
```
21
22
Resource management:
23
24
```python
25
from dependency_injector import resources
26
```
27
28
## Basic Usage
29
30
```python
31
from dependency_injector import containers, providers
32
from dependency_injector.wiring import Provide, inject
33
34
# Define services
35
class Database:
36
def __init__(self, connection_string: str):
37
self.connection_string = connection_string
38
39
def query(self, sql: str):
40
return f"Executing: {sql}"
41
42
class UserService:
43
def __init__(self, database: Database):
44
self.database = database
45
46
def get_user(self, user_id: int):
47
return self.database.query(f"SELECT * FROM users WHERE id = {user_id}")
48
49
# Create container with providers
50
class Container(containers.DeclarativeContainer):
51
# Configuration provider
52
config = providers.Configuration()
53
54
# Singleton database connection
55
database = providers.Singleton(
56
Database,
57
config.database.connection_string,
58
)
59
60
# Factory for user service instances
61
user_service = providers.Factory(
62
UserService,
63
database=database,
64
)
65
66
# Configure and wire dependencies
67
container = Container()
68
container.config.database.connection_string.from_value("postgresql://localhost/mydb")
69
container.wire(modules=[__name__])
70
71
# Use dependency injection
72
@inject
73
def main(user_service: UserService = Provide[Container.user_service]):
74
user = user_service.get_user(123)
75
print(user)
76
77
if __name__ == "__main__":
78
main()
79
```
80
81
## Architecture
82
83
The dependency injector framework is built around several key components:
84
85
- **Providers**: Factory objects that create and manage dependencies (Factory, Singleton, Callable, Configuration, Resource, etc.)
86
- **Containers**: Collections of providers that define the application's dependency graph
87
- **Wiring**: Automatic dependency injection into functions and methods using decorators and markers
88
- **Resources**: Lifecycle-managed objects with initialization and cleanup support
89
- **Configuration**: Multi-source configuration management with type conversion and validation
90
91
This design enables clean separation of concerns, testable code through provider overriding, and flexible dependency management across different environments and frameworks.
92
93
## Capabilities
94
95
### Provider System
96
97
Complete set of provider types for dependency creation and management including factories, singletons, callables, configurations, resources, collections, and dependency placeholders.
98
99
```python { .api }
100
class Provider:
101
def __call__(self, *args, **kwargs): ...
102
def override(self, provider): ...
103
def reset_override(self): ...
104
105
class Factory(Provider):
106
def __init__(self, provides, *args, **kwargs): ...
107
108
class Singleton(Provider):
109
def __init__(self, provides, *args, **kwargs): ...
110
def reset(self): ...
111
112
class Configuration(Provider):
113
def __init__(self, name="config"): ...
114
def from_yaml(self, filepath): ...
115
def from_env(self, name, default=None): ...
116
```
117
118
[Provider System](./providers.md)
119
120
### Container Management
121
122
Container classes for organizing providers with support for declarative and dynamic configuration, provider overriding, dependency wiring, and resource lifecycle management.
123
124
```python { .api }
125
class Container:
126
def wire(self, modules=None, packages=None): ...
127
def unwire(self): ...
128
def override(self, overriding): ...
129
def reset_singletons(self): ...
130
131
class DeclarativeContainer(Container): ...
132
133
class DynamicContainer(Container):
134
def set_providers(self, **providers): ...
135
```
136
137
[Container Management](./containers.md)
138
139
### Dependency Wiring
140
141
Decorators and markers for automatic dependency injection into functions, methods, and class attributes with support for synchronous and asynchronous code.
142
143
```python { .api }
144
def inject(fn): ...
145
146
def wire(container, modules=None, packages=None): ...
147
148
class Provide:
149
def __class_getitem__(cls, provider): ...
150
151
class Provider:
152
def __class_getitem__(cls, provider): ...
153
```
154
155
[Dependency Wiring](./wiring.md)
156
157
### Resource Management
158
159
Base classes and providers for managing resource lifecycles with automatic initialization and cleanup support for both synchronous and asynchronous resources.
160
161
```python { .api }
162
class Resource:
163
def init(self, *args, **kwargs): ...
164
def shutdown(self, resource): ...
165
166
class AsyncResource:
167
async def init(self, *args, **kwargs): ...
168
async def shutdown(self, resource): ...
169
```
170
171
[Resource Management](./resources.md)
172
173
### Schema Processing
174
175
Utilities for creating containers from configuration schemas with support for dynamic provider creation and dependency graph construction.
176
177
```python { .api }
178
class SchemaProcessorV1:
179
def __init__(self, schema): ...
180
def process(self): ...
181
def get_providers(self): ...
182
```
183
184
[Schema Processing](./schema.md)
185
186
### Framework Extensions
187
188
Integration modules for popular Python web frameworks, providing specialized providers and utilities for framework-specific dependency injection.
189
190
```python { .api }
191
# Flask extension (deprecated since v4.0.0)
192
from dependency_injector.ext.flask import Application, Extension, View, ClassBasedView
193
194
# Aiohttp extension (deprecated since v4.0.0)
195
from dependency_injector.ext.aiohttp import Application, Extension, Middleware, View, ClassBasedView
196
197
# Starlette extension
198
from dependency_injector.ext.starlette import Lifespan
199
```
200
201
**Note:** Flask and Aiohttp extensions are deprecated since version 4.0.0. Use the core dependency injection features directly with these frameworks instead.
202
203
## Error Handling
204
205
The framework defines specific exceptions for dependency injection errors:
206
207
```python { .api }
208
class Error(Exception):
209
"""Base exception for dependency injection errors."""
210
211
class NoSuchProviderError(Error, AttributeError):
212
"""Raised when accessing non-existent provider attributes."""
213
214
class NonCopyableArgumentError(Error):
215
"""Raised when trying to copy providers with non-copyable arguments."""
216
@property
217
def index(self): ...
218
@property
219
def keyword(self): ...
220
@property
221
def provider(self): ...
222
```
223
224
These exceptions help identify configuration and runtime issues in dependency injection setups. The framework provides specific error types to help developers quickly identify and resolve dependency injection problems.