0
# Dishka
1
2
A comprehensive Python dependency injection framework designed for applications that need sophisticated object lifecycle management and clean dependency handling. Dishka provides advanced scoping capabilities, automatic finalization for resources, modular provider architecture, and seamless integration with popular Python frameworks.
3
4
## Package Information
5
6
- **Package Name**: dishka
7
- **Language**: Python
8
- **Installation**: `pip install dishka`
9
- **Requirements**: Python >=3.10
10
11
## Core Imports
12
13
```python
14
import dishka
15
```
16
17
Common usage imports:
18
19
```python
20
from dishka import Container, Provider, Scope, make_container
21
from dishka import provide, alias, decorate, from_context
22
from dishka import FromDishka, FromComponent
23
```
24
25
Framework integration imports:
26
27
```python
28
from dishka.integrations.fastapi import setup_dishka, inject, FromDishka
29
from dishka.integrations.flask import setup_dishka, inject, FromDishka
30
from dishka.integrations.aiohttp import setup_dishka, inject, FromDishka
31
```
32
33
## Basic Usage
34
35
```python
36
from dishka import Provider, Scope, make_container, provide
37
from typing import Protocol
38
39
# Define your interfaces and classes
40
class Database(Protocol):
41
def execute(self, query: str) -> list: ...
42
43
class PostgreSQLDatabase:
44
def __init__(self, connection_string: str):
45
self.connection_string = connection_string
46
47
def execute(self, query: str) -> list:
48
# Implementation here
49
return []
50
51
class UserService:
52
def __init__(self, db: Database):
53
self.db = db
54
55
def get_users(self) -> list:
56
return self.db.execute("SELECT * FROM users")
57
58
# Create provider
59
provider = Provider()
60
provider.provide(PostgreSQLDatabase, provides=Database, scope=Scope.APP)
61
provider.provide(UserService, scope=Scope.REQUEST)
62
63
@provider.provide(scope=Scope.APP)
64
def get_connection_string() -> str:
65
return "postgresql://localhost/mydb"
66
67
# Create container
68
container = make_container(provider)
69
70
# Use dependencies
71
with container() as request_container:
72
user_service = request_container.get(UserService)
73
users = user_service.get_users()
74
75
container.close()
76
```
77
78
## Architecture
79
80
Dishka's architecture is built around several key concepts:
81
82
- **Container**: Central registry that manages dependency creation and lifecycle, with support for both sync and async operations
83
- **Provider**: Modular units that define how dependencies are created, allowing clean separation of factory logic
84
- **Scope**: Hierarchical lifecycle management (APP → REQUEST → ACTION → STEP) with automatic cleanup
85
- **Component**: Isolation system that allows multiple implementations of the same interface to coexist
86
- **Registry**: Internal dependency graph that validates and optimizes dependency resolution at startup
87
88
This design enables complex applications to maintain clean dependency boundaries while providing high performance and comprehensive lifecycle management.
89
90
## Capabilities
91
92
### Container Management
93
94
Core container functionality for creating, configuring, and managing dependency injection containers with lifecycle management and scope handling.
95
96
```python { .api }
97
def make_container(*providers, scopes=Scope, context=None, skip_validation=False) -> Container: ...
98
def make_async_container(*providers, scopes=Scope, context=None, skip_validation=False) -> AsyncContainer: ...
99
```
100
101
```python { .api }
102
class Container:
103
def get(self, dependency_type: type[T], component: str = "") -> T: ...
104
def __call__(self, context=None, scope=None) -> ContextManager[Container]: ...
105
def close(self, exception=None) -> None: ...
106
107
class AsyncContainer:
108
async def get(self, dependency_type: type[T], component: str = "") -> T: ...
109
def __call__(self, context=None, scope=None) -> AsyncContextManager[AsyncContainer]: ...
110
async def close(self, exception=None) -> None: ...
111
```
112
113
[Container Management](./container-management.md)
114
115
### Provider System
116
117
Modular provider classes and dependency registration functions for creating reusable dependency factories with flexible configuration options.
118
119
```python { .api }
120
class Provider:
121
def __init__(self, scope: BaseScope = None, component: str = None): ...
122
def provide(self, source, *, scope=None, provides=None, cache=True) -> None: ...
123
def alias(self, source, *, provides=None, cache=True, component=None) -> None: ...
124
125
def provide(*, scope=None, provides=None, cache=True, recursive=False, override=False): ...
126
def alias(source, *, provides=None, cache=True, component=None, override=False): ...
127
def decorate(*, provides=None): ...
128
def from_context(provides, *, scope=None, override=False): ...
129
```
130
131
[Provider System](./provider-system.md)
132
133
### Scope and Lifecycle Management
134
135
Hierarchical scope system for managing dependency lifetimes from application-wide to per-request or custom granular levels.
136
137
```python { .api }
138
class Scope(BaseScope):
139
RUNTIME: ClassVar[Scope]
140
APP: ClassVar[Scope]
141
SESSION: ClassVar[Scope]
142
REQUEST: ClassVar[Scope]
143
ACTION: ClassVar[Scope]
144
STEP: ClassVar[Scope]
145
146
class BaseScope:
147
name: str
148
skip: bool
149
150
def new_scope(value: str, *, skip: bool = False) -> BaseScope: ...
151
```
152
153
[Scope and Lifecycle Management](./scope-lifecycle.md)
154
155
### Type Markers and Injection
156
157
Type annotation markers and dependency key system for clean type-safe dependency injection without polluting business logic code.
158
159
```python { .api }
160
class FromDishka[T]:
161
"""Type marker for dependency injection"""
162
pass
163
164
class FromComponent:
165
def __call__(self, component: str = "") -> FromComponent: ...
166
167
class AnyOf[*Args]:
168
"""Marker for multiple possible dependency types"""
169
pass
170
171
class WithParents[T]:
172
"""Automatically provide all parent classes/interfaces"""
173
pass
174
175
class DependencyKey:
176
type_hint: Any
177
component: str | None
178
def with_component(self, component: str) -> DependencyKey: ...
179
```
180
181
[Type Markers and Injection](./type-markers.md)
182
183
### Framework Integrations
184
185
Ready-to-use integrations for popular Python frameworks with automatic dependency injection setup and middleware configuration.
186
187
```python { .api }
188
# Common pattern across integrations
189
def setup_dishka(container: Container, app: Any) -> None: ...
190
def inject(func: Callable) -> Callable: ...
191
```
192
193
Available integrations: FastAPI, Flask, Starlette, AIOhttp, Sanic, Litestar, gRPCio, Celery, Aiogram, Click, TaskIQ, FastStream, Telebot, ARQ
194
195
[Framework Integrations](./framework-integrations.md)
196
197
### Component System
198
199
Multi-component dependency isolation system allowing different implementations of the same interface to coexist within a single container.
200
201
```python { .api }
202
Component = str
203
DEFAULT_COMPONENT: str = ""
204
```
205
206
[Component System](./component-system.md)
207
208
### Validation and Configuration
209
210
Comprehensive validation system for dependency graphs with configurable validation rules and error detection.
211
212
```python { .api }
213
class ValidationSettings:
214
nothing_overridden: bool = False
215
implicit_override: bool = False
216
nothing_decorated: bool = True
217
218
STRICT_VALIDATION: ValidationSettings
219
```
220
221
[Validation and Configuration](./validation-configuration.md)
222
223
## Types
224
225
```python { .api }
226
T = TypeVar('T')
227
Component = str
228
DEFAULT_COMPONENT: str = ""
229
230
class DependencyKey(NamedTuple):
231
type_hint: Any
232
component: Component | None
233
234
def with_component(self, component: Component) -> DependencyKey: ...
235
def __str__(self) -> str: ...
236
237
class ValidationSettings:
238
nothing_overridden: bool
239
implicit_override: bool
240
nothing_decorated: bool
241
242
STRICT_VALIDATION: ValidationSettings
243
DEFAULT_VALIDATION: ValidationSettings
244
245
class BaseScope:
246
name: str
247
skip: bool
248
```