Skip to main content

Modern-DI integration for LiteStar

Project description

modern-di-litestar

PyPI version Supported Python versions Downloads Coverage CI License GitHub stars uv Ruff ty

Modern-DI integration for Litestar.

Usage example: litestar-sqlalchemy-template

Installation

uv add modern-di-litestar      # or: pip install modern-di-litestar

Usage

1. Define providers

import dataclasses
from modern_di import Group, Scope, providers


@dataclasses.dataclass(kw_only=True)
class Database:
    url: str


@dataclasses.dataclass(kw_only=True)
class UserRepository:
    db: Database


class AppDependencies(Group):
    database = providers.Factory(creator=Database, kwargs={"url": "sqlite:///app.db"})
    user_repo = providers.Factory(scope=Scope.REQUEST, creator=UserRepository, bound_type=None)

2. Wire the plugin

import litestar
from modern_di import Container
from modern_di_litestar import ModernDIPlugin

groups = [AppDependencies]

app = litestar.Litestar(
    plugins=[ModernDIPlugin(Container(groups=groups), autowired_groups=groups)],
)

Passing autowired_groups to ModernDIPlugin auto-registers each provider as a Litestar dependency keyed by its attribute name (database, user_repo), so routes can declare them directly as parameters.

3. Inject into routes

Using FromDI (explicit, per-route)

from modern_di_litestar import FromDI

@litestar.get(
    "/users",
    dependencies={"repo": FromDI(AppDependencies.user_repo)},
)
async def list_users(repo: UserRepository) -> list[str]:
    ...

FromDI accepts either a provider instance (AppDependencies.user_repo) or a type (UserRepository).

Using auto-wired group names (implicit)

When autowired_groups is passed to ModernDIPlugin, provider names become available as route parameters directly:

@litestar.get("/users")
async def list_users(user_repo: UserRepository) -> list[str]:
    ...

4. Access the raw request or websocket via DI

from modern_di_litestar import litestar_request_provider, litestar_websocket_provider

class AppDependencies(Group):
    ...
    request_method = providers.Factory(
        scope=Scope.REQUEST,
        creator=lambda request: request.method,
        bound_type=None,
    )

litestar_request_provider and litestar_websocket_provider are pre-built ContextProvider instances that make the current Request / WebSocket objects resolvable within DI.

5. Sub-request (action) scopes

For work that should live shorter than a request, build a child container inside a route:

@litestar.get("/")
async def handler(di_container: Container) -> None:
    action_container = di_container.build_child_container()
    result = action_container.resolve_provider(AppDependencies.some_action_scoped_factory)

6. Retrieve the app-level container

from modern_di_litestar import fetch_di_container

container = fetch_di_container(app)

API

Symbol Description
ModernDIPlugin(container, autowired_groups=None) Litestar InitPlugin — wires the DI container into app lifecycle
FromDI(provider) Returns a Litestar Provide that resolves a provider per request
litestar_request_provider ContextProvider for the current litestar.Request
litestar_websocket_provider ContextProvider for the current litestar.WebSocket
fetch_di_container(app) Retrieves the root container from app.state
build_di_container Litestar dependency (registered as di_container) — yields a scoped child container per request

📦 PyPI

📝 License

Part of modern-python

Browse the full list of templates and libraries in modern-python — see the org profile for the categorized index.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

modern_di_litestar-2.9.2.tar.gz (4.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

modern_di_litestar-2.9.2-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

Details for the file modern_di_litestar-2.9.2.tar.gz.

File metadata

  • Download URL: modern_di_litestar-2.9.2.tar.gz
  • Upload date:
  • Size: 4.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for modern_di_litestar-2.9.2.tar.gz
Algorithm Hash digest
SHA256 3bc342af9c3d36533c09a1d3b244f343f74db02a76426546935ef800c3c25225
MD5 835a51c1fedfaca02c5513e6493541da
BLAKE2b-256 af18917d48c7864379bb9d5a74a18161d8fc2550631d94c5806aa6d9b3d64c05

See more details on using hashes here.

File details

Details for the file modern_di_litestar-2.9.2-py3-none-any.whl.

File metadata

  • Download URL: modern_di_litestar-2.9.2-py3-none-any.whl
  • Upload date:
  • Size: 5.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.21 {"installer":{"name":"uv","version":"0.11.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for modern_di_litestar-2.9.2-py3-none-any.whl
Algorithm Hash digest
SHA256 380af52220a6f6d062049446f9cdd83cb7f5170da881a75f30fda3d43c2ea705
MD5 e15755d7125992569f3e3e93b407dc68
BLAKE2b-256 1c9cd072925760d495949c5e8a2d67d0bc221420e039f7eb26e4c563fdfa029e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page