0
# Provider System
1
2
The provider system is the core of the dependency injection framework, offering various provider types for creating, managing, and configuring dependencies. Providers are factory objects that know how to create instances with proper dependency injection.
3
4
## Capabilities
5
6
### Base Provider Classes
7
8
Foundation classes that define the provider interface and common functionality.
9
10
```python { .api }
11
class Provider:
12
"""Base provider class with overriding and lifecycle management."""
13
def __call__(self, *args, **kwargs): ...
14
def async_(self, *args, **kwargs): ...
15
def override(self, provider): ...
16
def reset_override(self): ...
17
def delegate(self): ...
18
@property
19
def provided(self): ...
20
def traverse(self, types=None): ...
21
def enable_async_mode(self): ...
22
def disable_async_mode(self): ...
23
@property
24
def is_async_mode_enabled(self): ...
25
@property
26
def overridden(self): ...
27
@property
28
def last_overriding(self): ...
29
30
class Object(Provider):
31
"""Provider for static objects and instances."""
32
def __init__(self, provides=None): ...
33
def set_provides(self, provides): ...
34
35
class Self(Provider):
36
"""Provider for container self-reference."""
37
def __init__(self, container=None): ...
38
def set_container(self, container): ...
39
40
class Delegate(Provider):
41
"""Provider delegation wrapper."""
42
def __init__(self, provides=None): ...
43
```
44
45
### Factory Providers
46
47
Providers that create new instances on each call, supporting constructor injection and attribute setting.
48
49
```python { .api }
50
class Factory(Provider):
51
"""Creates new instances on each call."""
52
def __init__(self, provides, *args, **kwargs): ...
53
@property
54
def provides(self): ...
55
def set_provides(self, provides): ...
56
def add_args(self, *args): ...
57
def set_args(self, *args): ...
58
def add_kwargs(self, **kwargs): ...
59
def set_kwargs(self, **kwargs): ...
60
def add_attributes(self, **kwargs): ...
61
def set_attributes(self, **kwargs): ...
62
63
class DelegatedFactory(Factory):
64
"""Delegated factory variant."""
65
66
class AbstractFactory(Factory):
67
"""Abstract factory for overriding."""
68
```
69
70
Usage example:
71
72
```python
73
class Database:
74
def __init__(self, host, port, username, password):
75
self.host = host
76
self.port = port
77
self.username = username
78
self.password = password
79
80
# Factory with constructor arguments
81
database_factory = providers.Factory(
82
Database,
83
host="localhost",
84
port=5432,
85
username="admin",
86
password="secret"
87
)
88
89
# Create instances
90
db1 = database_factory()
91
db2 = database_factory() # Creates a new instance
92
```
93
94
### Singleton Providers
95
96
Providers that create a single instance and return the same instance on subsequent calls.
97
98
```python { .api }
99
class BaseSingleton(Provider):
100
"""Base singleton with lifecycle management."""
101
def __init__(self, provides, *args, **kwargs): ...
102
@property
103
def provides(self): ...
104
def add_args(self, *args): ...
105
def set_args(self, *args): ...
106
def add_kwargs(self, **kwargs): ...
107
def set_kwargs(self, **kwargs): ...
108
def add_attributes(self, **kwargs): ...
109
def set_attributes(self, **kwargs): ...
110
def reset(self): ...
111
def full_reset(self): ...
112
113
class Singleton(BaseSingleton):
114
"""Standard singleton implementation."""
115
116
class ThreadSafeSingleton(Singleton):
117
"""Thread-safe singleton."""
118
119
class ThreadLocalSingleton(BaseSingleton):
120
"""Thread-local singleton."""
121
122
class ContextLocalSingleton(BaseSingleton):
123
"""Context-local singleton."""
124
125
class DelegatedSingleton(Singleton):
126
"""Delegated singleton variant."""
127
128
class DelegatedThreadSafeSingleton(ThreadSafeSingleton):
129
"""Delegated thread-safe singleton variant."""
130
131
class DelegatedThreadLocalSingleton(ThreadLocalSingleton):
132
"""Delegated thread-local singleton variant."""
133
134
class AbstractSingleton(BaseSingleton):
135
"""Abstract singleton for overriding."""
136
```
137
138
Usage example:
139
140
```python
141
# Singleton database connection
142
database = providers.Singleton(
143
Database,
144
host="localhost",
145
port=5432
146
)
147
148
# Always returns the same instance
149
db1 = database()
150
db2 = database() # Same instance as db1
151
assert db1 is db2
152
```
153
154
### Callable Providers
155
156
Providers that call functions or methods with dependency injection.
157
158
```python { .api }
159
class Callable(Provider):
160
"""Calls functions/methods with injected arguments."""
161
def __init__(self, provides, *args, **kwargs): ...
162
@property
163
def provides(self): ...
164
def set_provides(self, provides): ...
165
def add_args(self, *args): ...
166
def set_args(self, *args): ...
167
def add_kwargs(self, **kwargs): ...
168
def set_kwargs(self, **kwargs): ...
169
170
class Coroutine(Callable):
171
"""Async coroutine provider."""
172
173
class DelegatedCallable(Callable):
174
"""Delegated callable variant."""
175
```
176
177
Usage example:
178
179
```python
180
def create_connection(host, port):
181
return f"Connected to {host}:{port}"
182
183
# Callable provider
184
connection_provider = providers.Callable(
185
create_connection,
186
host="localhost",
187
port=5432
188
)
189
190
connection = connection_provider() # Calls the function
191
```
192
193
### Configuration Providers
194
195
Providers for managing application configuration from multiple sources.
196
197
```python { .api }
198
class Configuration(Provider):
199
"""Configuration management with multiple source support."""
200
def __init__(self, name="config", default=None, strict=False): ...
201
def __getattr__(self, item): ...
202
def __getitem__(self, item): ...
203
def from_yaml(self, filepath, required=False): ...
204
def from_json(self, filepath, required=False): ...
205
def from_ini(self, filepath, required=False): ...
206
def from_env(self, name, default=None, required=False): ...
207
def from_dict(self, options, required=False): ...
208
def from_pydantic(self, settings, required=False): ...
209
def update(self, value): ...
210
def get(self, selector): ...
211
def set(self, selector, value): ...
212
213
class ConfigurationOption(Provider):
214
"""Individual configuration option with type conversion."""
215
def as_int(self): ...
216
def as_float(self): ...
217
def as_(self, callback, *args, **kwargs): ...
218
def required(self): ...
219
def update(self, value): ...
220
```
221
222
Usage example:
223
224
```python
225
# Configuration provider
226
config = providers.Configuration()
227
228
# Load from multiple sources
229
config.from_yaml("config.yaml")
230
config.from_env("DATABASE_URL", default="sqlite:///app.db")
231
232
# Access configuration values
233
database_url = config.database.url()
234
debug_mode = config.debug.as_(bool)()
235
port = config.server.port.as_int()
236
```
237
238
### Collection Providers
239
240
Providers for creating collections with injected dependencies.
241
242
```python { .api }
243
class List(Provider):
244
"""Provides list of injected values."""
245
def __init__(self, *args): ...
246
def add_args(self, *args): ...
247
def set_args(self, *args): ...
248
249
class Dict(Provider):
250
"""Provides dictionary of injected values."""
251
def __init__(self, dict_=None, **kwargs): ...
252
def add_kwargs(self, dict_=None, **kwargs): ...
253
def set_kwargs(self, dict_=None, **kwargs): ...
254
```
255
256
Usage example:
257
258
```python
259
# List provider
260
services = providers.List(
261
user_service,
262
email_service,
263
notification_service
264
)
265
266
# Dict provider
267
endpoints = providers.Dict(
268
users="/api/users",
269
posts="/api/posts",
270
comments="/api/comments"
271
)
272
```
273
274
### Resource Providers
275
276
Providers for managing resource lifecycles with initialization and cleanup.
277
278
```python { .api }
279
class Resource(Provider):
280
"""Resource lifecycle management provider."""
281
def __init__(self, provides, *args, **kwargs): ...
282
@property
283
def provides(self): ...
284
def add_args(self, *args): ...
285
def set_args(self, *args): ...
286
def add_kwargs(self, **kwargs): ...
287
def set_kwargs(self, **kwargs): ...
288
@property
289
def initialized(self): ...
290
def init(self): ...
291
def shutdown(self): ...
292
```
293
294
Usage example:
295
296
```python
297
from dependency_injector.resources import Resource
298
299
class DatabaseResource(Resource):
300
def init(self, connection_string):
301
# Initialize database connection
302
connection = create_connection(connection_string)
303
return connection
304
305
def shutdown(self, connection):
306
# Close database connection
307
connection.close()
308
309
# Resource provider
310
database = providers.Resource(
311
DatabaseResource,
312
connection_string="postgresql://localhost/mydb"
313
)
314
```
315
316
### Dependency Providers
317
318
Providers for defining abstract dependencies that can be overridden.
319
320
```python { .api }
321
class Dependency(Provider):
322
"""Abstract dependency placeholder."""
323
def __init__(self, instance_of=object, default=None): ...
324
@property
325
def instance_of(self): ...
326
def set_instance_of(self, instance_of): ...
327
@property
328
def default(self): ...
329
def set_default(self, default): ...
330
def provided_by(self, provider): ...
331
332
class ExternalDependency(Dependency):
333
"""External dependency variant."""
334
335
class DependenciesContainer(Provider):
336
"""Container for dependency providers."""
337
def __init__(self, **dependencies): ...
338
```
339
340
### Aggregate and Selection Providers
341
342
Providers for grouping multiple providers and conditional selection.
343
344
```python { .api }
345
class Aggregate(Provider):
346
"""Aggregate of multiple providers."""
347
def __init__(self, provider_dict=None, **provider_kwargs): ...
348
@property
349
def providers(self): ...
350
def set_providers(self, provider_dict=None, **provider_kwargs): ...
351
352
class Selector(Provider):
353
"""Conditional provider selection."""
354
def __init__(self, selector=None, **providers): ...
355
@property
356
def selector(self): ...
357
def set_selector(self, selector): ...
358
@property
359
def providers(self): ...
360
def set_providers(self, **providers): ...
361
```
362
363
### Provider Interface Utilities
364
365
Fluent interface for accessing provider results and performing operations.
366
367
```python { .api }
368
class ProvidedInstance:
369
"""Fluent interface for provider.provided access."""
370
def __getattr__(self, item): ...
371
def __getitem__(self, item): ...
372
def call(self, *args, **kwargs): ...
373
374
class AttributeGetter(Provider):
375
"""Attribute access provider."""
376
def __init__(self, provides=None, name=None): ...
377
378
class ItemGetter(Provider):
379
"""Item access provider."""
380
def __init__(self, provides=None, name=None): ...
381
382
class MethodCaller(Provider):
383
"""Method call provider."""
384
def __init__(self, provides=None, *args, **kwargs): ...
385
```
386
387
## Utility Functions
388
389
Helper functions for working with providers.
390
391
```python { .api }
392
def is_provider(instance) -> bool:
393
"""Check if object is a provider."""
394
395
def ensure_is_provider(instance) -> Provider:
396
"""Ensure object is a provider."""
397
398
def is_delegated(instance) -> bool:
399
"""Check if provider is delegated."""
400
401
def deepcopy(instance, memo=None):
402
"""Deep copy providers with memoization."""
403
404
def traverse(*providers, types=None):
405
"""Traverse provider graph."""
406
407
def represent_provider(provider, indent=0) -> str:
408
"""Return string representation of provider structure."""
409
```
410
411
## Context Managers
412
413
Context managers for managing provider overrides and singleton lifecycle.
414
415
```python { .api }
416
class OverridingContext:
417
"""Context manager for temporary provider overriding."""
418
def __init__(self, overridden, overriding): ...
419
def __enter__(self): ...
420
def __exit__(self, *exc_info): ...
421
422
class SingletonResetContext:
423
"""Context manager for singleton reset."""
424
def __init__(self, provider): ...
425
def __enter__(self): ...
426
def __exit__(self, *exc_info): ...
427
428
class SingletonFullResetContext:
429
"""Context manager for full singleton reset."""
430
def __init__(self, provider): ...
431
def __enter__(self): ...
432
def __exit__(self, *exc_info): ...
433
```