From 0bc9239f373af8fd781fa3eb4c9735e8c533d9c8 Mon Sep 17 00:00:00 2001 From: Artur Shiriev Date: Thu, 2 Jul 2026 10:52:24 +0300 Subject: [PATCH] docs: add Starlette integration usage page Usage page for the new modern-di-starlette integration (decorator path: setup_di + @inject/FromDI), plus a nav entry under Integrations. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs/integrations/starlette.md | 63 ++++++++++++++++++++++++++++++++++ mkdocs.yml | 1 + 2 files changed, 64 insertions(+) create mode 100644 docs/integrations/starlette.md diff --git a/docs/integrations/starlette.md b/docs/integrations/starlette.md new file mode 100644 index 0000000..4f4235c --- /dev/null +++ b/docs/integrations/starlette.md @@ -0,0 +1,63 @@ +# Usage with `Starlette` + +Starlette has no dependency-injection system of its own, so `modern-di-starlette` +uses the `@inject` decorator with `FromDI` markers (there is no `Depends`). +`setup_di` composes the lifespan and installs middleware that opens a +per-connection child container automatically. + +## How to use + +### 1. Install `modern-di-starlette` + +=== "uv" + + ```bash + uv add modern-di-starlette + ``` + +=== "pip" + + ```bash + pip install modern-di-starlette + ``` + +### 2. Apply to your application + +```python +import dataclasses +import typing + +from modern_di import Container, Group, Scope, providers +from modern_di_starlette import FromDI, inject, setup_di +from starlette.applications import Starlette +from starlette.requests import Request +from starlette.responses import JSONResponse +from starlette.routing import Route + + +@dataclasses.dataclass(kw_only=True) +class Settings: + debug: bool = True + + +class AppGroup(Group): + settings = providers.Factory(scope=Scope.APP, creator=Settings) + + +@inject +async def homepage( + request: Request, + settings: typing.Annotated[Settings, FromDI(AppGroup.settings)], +) -> JSONResponse: + return JSONResponse({"debug": settings.debug}) + + +app = Starlette(routes=[Route("/", homepage)]) +setup_di(app, Container(groups=[AppGroup], validate=True)) +``` + +### 3. Scopes + +An HTTP request opens a `Scope.REQUEST` child container; a WebSocket connection +opens a `Scope.SESSION` one. Providers resolve from the connection's child +container, so `Scope.REQUEST` providers live for exactly one request. diff --git a/mkdocs.yml b/mkdocs.yml index a883d64..83df5bb 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -24,6 +24,7 @@ nav: - FastAPI: integrations/fastapi.md - FastStream: integrations/faststream.md - Litestar: integrations/litestar.md + - Starlette: integrations/starlette.md - Typer: integrations/typer.md - Pytest: integrations/pytest.md - Writing an integration: integrations/writing-integrations.md