Skip to content

Dishka Dependency Injection

Dishka is a scoped IoC container for Python applications that share dependencies across HTTP servers (Litestar, FastAPI, Starlette, Flask, Sanic), background worker queues, and CLI entrypoints. SQLSpec's explicit separation between application-scoped *Config pools and request-scoped *Driver sessions maps directly onto Dishka's Scope.APP and Scope.REQUEST scopes.

Installation

uv add sqlspec dishka
pip install sqlspec dishka
pdm add sqlspec dishka
poetry add sqlspec dishka

Provider Pattern for App and Request Scopes

Register SQLSpec and your adapter *Config at Scope.APP (created once per process, closing the pool when the application container closes) and yield the driver session from sqlspec.provide_session(config) at Scope.REQUEST:

Dishka Scope SQLSpec Object Lifecycle Responsibility
Scope.APP SQLSpec registry + *Config (AsyncpgConfig, SqliteConfig, etc.) Created once at process startup; await config.close_pool() / config.close_pool() runs on container shutdown Owns the underlying database connection pool, statement cache, and SQLFileLoader
Scope.REQUEST *Driver (AsyncpgDriver, SqliteDriver, etc.) and SQLSpecAsyncService / SQLSpecSyncService Entered per HTTP request, CLI command, or worker task via async with spec.provide_session(config) as driver: Borrows one connection from the Scope.APP pool, executes queries/transactions, and returns the connection on scope exit
from collections.abc import AsyncIterator

from dishka import Provider, Scope, provide

from sqlspec import SQLSpec
from sqlspec.adapters.asyncpg import AsyncpgConfig, AsyncpgDriver


class DatabaseProvider(Provider):
    @provide(scope=Scope.APP)
    async def provide_config(
        self,
    ) -> AsyncIterator[tuple[SQLSpec, AsyncpgConfig]]:
        spec = SQLSpec()
        config = spec.add_config(
            AsyncpgConfig(
                connection_config={
                    "dsn": "postgresql://localhost/mydb",
                    "min_size": 2,
                    "max_size": 20,
                }
            )
        )
        try:
            yield spec, config
        finally:
            await config.close_pool()

    @provide(scope=Scope.REQUEST)
    async def provide_driver(
        self, app_deps: tuple[SQLSpec, AsyncpgConfig]
    ) -> AsyncIterator[AsyncpgDriver]:
        spec, config = app_deps
        async with spec.provide_session(config) as driver:
            yield driver

Injecting Drivers into Domain Services

Register SQLSpecAsyncService (or SQLSpecSyncService) subclasses at Scope.REQUEST. Dishka resolves the constructor's driver annotation from the request-scoped provider, so each service receives the driver for the current request:

from typing import Any

from dishka import Provider, Scope, provide

from sqlspec.adapters.asyncpg import AsyncpgDriver
from sqlspec.service import SQLSpecAsyncService


class UserService(SQLSpecAsyncService[AsyncpgDriver]):
    def __init__(self, driver: AsyncpgDriver) -> None:
        super().__init__(session=driver)

    async def get_user(self, user_id: int) -> dict[str, Any]:
        return await self.get_one(
            "SELECT id, email FROM users WHERE id = :id", id=user_id
        )


class ServiceProvider(Provider):
    user_service = provide(UserService, scope=Scope.REQUEST)

Reusing the Container Across Entrypoints

Build one container per process and open a request scope for each unit of work, whether it comes from an HTTP route, a CLI command, or a worker task:

from dishka import make_async_container


async def main() -> None:
    container = make_async_container(DatabaseProvider(), ServiceProvider())
    try:
        async with container() as request_container:
            users = await request_container.get(UserService)
            await users.get_user(1)
    finally:
        await container.close()

Recap

  • Provide SQLSpec and *Config at Scope.APP (closing pools in finally:) and yield spec.provide_session(config) at Scope.REQUEST.
  • Register Service Layer classes (SQLSpecAsyncService / SQLSpecSyncService) at Scope.REQUEST to share query logic across web routes, CLI commands, and background workers, and use FromDishka[...] in framework route handlers.