import asyncio from uuid import uuid4 from fastapi import Depends, FastAPI from dependency_injector import containers, providers from dependency_injector.wiring import Closing, Provide, inject class AsyncSessionLocal: def __init__(self): self.id = uuid4() async def __aenter__(self): print("Entering session !") return self async def __aexit__(self, exc_type, exc_val, exc_tb): print("Closing session !") async def execute(self, user_input): await asyncio.sleep(0.1) return f"Executing {user_input} in session {self.id}" class APIRepository: @inject async def execute(self, user_input, db_session: AsyncSessionLocal = Provide["db_session"]): return await db_session.execute(user_input) app = FastAPI() class Container(containers.DeclarativeContainer): db_session = providers.ContextLocalResource(AsyncSessionLocal) api_repository = providers.Factory(APIRepository) @app.get("/") @inject async def index( db: AsyncSessionLocal = Depends(Closing[Provide["db_session"]]), api_repository: APIRepository = Depends(Provide["api_repository"]), ): user_input = "SELECT 1" res = await db.execute(user_input) res_from_repo = await api_repository.execute(user_input=user_input) assert res == res_from_repo return str(res) if __name__ == "__main__": import uvicorn container = Container() container.wire(modules=["__main__"]) uvicorn.run(app, host="localhost", port=8000) container.unwire()