README.md
July 28, 2026 ยท View on GitHub
Modern-DI integration for taskiq.
Full guide: taskiq integration docs
Usage example: examples/
Installation
uv add modern-di-taskiq # or: pip install modern-di-taskiq
Usage
setup_di stores the container on broker.state and registers WORKER_STARTUP/WORKER_SHUTDOWN handlers that open/close it, and builds a Scope.REQUEST child container for each task the worker executes. FromDI resolves a provider (or type) into a task parameter โ no per-task decorator is needed.
import typing
from modern_di import Container, Group, Scope, providers
from modern_di_taskiq import FromDI, setup_di
from taskiq import InMemoryBroker
class Settings:
def __init__(self) -> None:
self.greeting = "hello"
class Greeter:
def __init__(self, settings: Settings) -> None: # auto-injected by type
self._settings = settings
def greet(self, name: str) -> str:
return f"{self._settings.greeting}, {name}"
class AppGroup(Group):
settings = providers.Factory(Settings, scope=Scope.APP, cache=True)
greeter = providers.Factory(Greeter, scope=Scope.REQUEST)
broker = InMemoryBroker()
container = Container(groups=[AppGroup])
setup_di(broker, container)
container.validate() # optional fail-fast; must come after setup_di registers its providers
@broker.task
async def greet(
name: str,
greeter: typing.Annotated[Greeter, FromDI(Greeter)], # resolve by type
) -> str:
return greeter.greet(name)
The WORKER_STARTUP/WORKER_SHUTDOWN events fire when the broker's worker process starts and stops, so a script that calls tasks directly (like InMemoryBroker in a test) must drive the container lifecycle itself โ e.g. async with broker: .... The per-task Scope.REQUEST child is torn down asynchronously (close_async()), so async REQUEST-scoped finalizers run correctly while factories build synchronously. taskiq.TaskiqMessage is resolvable within DI via the pre-built taskiq_message_provider context provider.
API
| Symbol | Description |
|---|---|
setup_di(broker, container) | Stores the APP-scope container on broker.state, opens/closes it on worker startup/shutdown, and builds a Scope.REQUEST child container per task. Returns the container |
FromDI(dependency) | Inert marker for Annotated[T, FromDI(...)] in task signatures; accepts a provider instance or a type |
fetch_di_container(broker) | Returns the APP-scope container registered with the taskiq broker |
taskiq_message_provider | ContextProvider for the current taskiq.TaskiqMessage (REQUEST scope) |
๐ฆ PyPI
๐ License
Part of modern-python
Built on modern-di, a dependency-injection framework with IoC container and scopes.
Browse the full list of templates and libraries in
modern-python โ see the org profile for the categorized index.