1+ import asyncio
12from uuid import uuid4
23
34from fastapi import Depends , FastAPI
45
56from dependency_injector import containers , providers
67from dependency_injector .wiring import Closing , Provide , inject
78
8- global_list = []
9-
109
1110class AsyncSessionLocal :
1211 def __init__ (self ):
@@ -20,23 +19,35 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
2019 print ("Closing session !" )
2120
2221 async def execute (self , user_input ):
22+ await asyncio .sleep (0.1 )
2323 return f"Executing { user_input } in session { self .id } "
2424
2525
26+ class APIRepository :
27+ @inject
28+ async def execute (self , user_input , db_session : AsyncSessionLocal = Provide ["db_session" ]):
29+ return await db_session .execute (user_input )
30+
31+
2632app = FastAPI ()
2733
2834
2935class Container (containers .DeclarativeContainer ):
3036 db_session = providers .ContextLocalResource (AsyncSessionLocal )
37+ api_repository = providers .Factory (APIRepository )
3138
3239
3340@app .get ("/" )
3441@inject
35- async def index (db : AsyncSessionLocal = Depends (Closing [Provide ["db_session" ]])):
36- if db .id in global_list :
37- raise Exception ("The db session is already used" ) # never reaches here
38- global_list .append (db .id )
39- res = await db .execute ("SELECT 1" )
42+ async def index (
43+ db : AsyncSessionLocal = Depends (Closing [Provide ["db_session" ]]),
44+ api_repository : APIRepository = Depends (Provide ["api_repository" ]),
45+ ):
46+ user_input = "SELECT 1"
47+ res = await db .execute (user_input )
48+ res_from_repo = await api_repository .execute (user_input = user_input )
49+ assert res == res_from_repo
50+
4051 return str (res )
4152
4253
0 commit comments