Skip to content

Commit 2293251

Browse files
committed
Add docs for ASGI Lifespan support
1 parent 1b4b3d3 commit 2293251

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

docs/api/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ API Documentation
99
containers
1010
wiring
1111
errors
12+
asgi-lifespan

docs/providers/resource.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,5 +401,54 @@ See also:
401401
- Wiring :ref:`async-injections-wiring`
402402
- :ref:`fastapi-redis-example`
403403

404+
ASGI Lifespan Protocol Support
405+
------------------------------
406+
407+
The :mod:`dependency_injector.ext.starlette` module provides a :class:`~dependency_injector.ext.starlette.Lifespan`
408+
class that integrates resource providers with ASGI applications using the `Lifespan Protocol`_. This allows resources to
409+
be automatically initialized at application startup and properly shut down when the application stops.
410+
411+
.. code-block:: python
412+
413+
from contextlib import asynccontextmanager
414+
from dependency_injector import containers, providers
415+
from dependency_injector.wiring import Provide, inject
416+
from dependency_injector.ext.starlette import Lifespan
417+
from fastapi import FastAPI, Request, Depends, APIRouter
418+
419+
class Connection: ...
420+
421+
@asynccontextmanager
422+
async def init_database():
423+
print("opening database connection")
424+
yield Connection()
425+
print("closing database connection")
426+
427+
router = APIRouter()
428+
429+
@router.get("/")
430+
@inject
431+
async def index(request: Request, db: Connection = Depends(Provide["db"])):
432+
# use the database connection here
433+
return "OK!"
434+
435+
class Container(containers.DeclarativeContainer):
436+
__self__ = providers.Self()
437+
db = providers.Resource(init_database)
438+
lifespan = providers.Singleton(Lifespan, __self__)
439+
app = providers.Singleton(FastAPI, lifespan=lifespan)
440+
_include_router = providers.Resource(
441+
app.provided.include_router.call(),
442+
router,
443+
)
444+
445+
if __name__ == "__main__":
446+
import uvicorn
447+
448+
container = Container()
449+
app = container.app()
450+
uvicorn.run(app, host="localhost", port=8000)
451+
452+
.. _Lifespan Protocol: https://asgi.readthedocs.io/en/latest/specs/lifespan.html
404453

405454
.. disqus::

0 commit comments

Comments
 (0)