@@ -401,5 +401,54 @@ See also:
401
401
- Wiring :ref: `async-injections-wiring `
402
402
- :ref: `fastapi-redis-example `
403
403
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
404
453
405
454
.. disqus ::
0 commit comments