🧪 Dependency Injection (DI)¶
Dispytch supports a FastAPI-style Dependency Injection system to cleanly manage your handler dependencies—keeping your logic modular, testable, and DRY.
💡 Why Use DI?¶
♻️ Decoupling – Separate business logic from infrastructure concerns
✅ Testability – Easily mock or override dependencies in tests
🔄 Reusability – Centralize shared resources and logic
How It Works¶
Handlers declare dependencies using Python’s type annotations combined with Dispytch’s Dependency wrapper and Event
generic class.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
At runtime, Dispytch:
-
Parses the handler signature.
-
Resolves dependencies using the provided factory functions (sync or async).
-
Injects results directly into the handler.
-
Handles cleanup automatically for context-managed dependencies.
🧩 Nested Dependencies¶
Dispytch supports dependency chains—where one dependency depends on another. Each layer is resolved automatically, with full lifecycle management.
✍️ Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
🔍 What's happening¶
get_servicedeclares a dependency onget_config- Dispytch resolves
get_config, then passes the result toget_service - The final resolved
Serviceis injected into the handler
🌐 Context-Aware Dependencies¶
Dependency functions can receive contextual information about the current event—such as its topic, type, or payload—by
accepting a typed Event[T] as an argument.
This enables runtime-aware logic, such as per-event logging, dynamic configuration, or tenant resolution.
✍️ Example¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
🔁 Alternative Syntax¶
As an alternative for the Annotated[T, Dependency(...)] style, Dispytch lets you inject dependencies by assigning a
Dependency instance directly as a default value for a handler parameter. Functionally the same—just a different
flavor.
📋 Note: This injection method does not work for the
Eventparameter. You must use explicit type hints forEventto enable proper injection.
✍️ Example¶
1 2 3 4 5 6 7 8 9 10 | |