I like this style of writing routes in FastAPI. But it seems to be flawed.
@router.get('/items', response_model=list[AvatarPropertyItemOut])
async def get_avatar_items(
service: Annotated[AvatarService, Depends(get_avatar_service)],
) -> list[AvatarPropertyItemOut]:
"""Get the list of avatar items."""
return await service.get_avatar_items()
async def get_avatar_service() -> AvatarService:
"""Get the avatar service."""
async with async_session_maker() as session:
avatar_repo = AvatarRepository(session)
return AvatarService(
avatar_repo=avatar_repo,
)
@asynccontextmanager
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
"""Get the database session."""
async with async_session_maker() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
But it seems like the object stays alive after the route is done.
So the connection to database doesn't get closed.
I don't really want to do the Depends in every route for getting session.
And writing session injection in every route.
And possibly passing session to every method of service classes.
Is there a way to make this approach possible? :\