Skip to content

Commit bb20c40

Browse files
author
Elina
committed
remove redundant objects, add nested injection
1 parent 3be8890 commit bb20c40

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

examples/providers/context_local_resource.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1+
import asyncio
12
from uuid import uuid4
23

34
from fastapi import Depends, FastAPI
45

56
from dependency_injector import containers, providers
67
from dependency_injector.wiring import Closing, Provide, inject
78

8-
global_list = []
9-
109

1110
class 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+
2632
app = FastAPI()
2733

2834

2935
class 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

Comments
 (0)