Skip to content

Conversation

Copy link

Copilot AI commented Nov 7, 2025

The problem statement asks how to properly annotate return types in dependency functions: ChatService() vs ChatService, and requests a principle-based explanation.

Changes

Added comprehensive documentation section "依赖注入的类型注解原理" to FastAPI框架.md covering:

  • Core principle: Use ChatService (type) not ChatService() (call expression) in type annotations
  • Annotated mechanics: First parameter is the type for type checkers, second is FastAPI metadata (Depends)
  • Dependency injection workflow: How FastAPI resolves, calls, validates, and injects dependencies
  • Complete examples: ChatService and CanvasService with correct/incorrect patterns
  • Summary table: Quick reference for return types, parameter types, and return values

Example

# Dependency function - return type uses the class (type)
chat_service = ChatService()

def get_chat_service() -> ChatService:  # ✅ Type annotation
    return chat_service  # ✅ Returns instance

# Route function - parameter uses Annotated with type and metadata
@router.get("/chat_session/{session_id}")
async def get_chat_session(
    session_id: str,
    chat_service: Annotated[ChatService, Depends(get_chat_service)]
):
    return await chat_service.get_chat_history(session_id=session_id)

Type annotations always use types (classes), never call expressions. The dependency system handles instantiation and injection at runtime.

Original prompt

@router.get("/chat_session/{session_id}")
async def get_chat_session(
session_id: str, chat_service=Annotated[ChatService, Depends(get_chat_service)]
):
return await chat_service.get_chat_history(session_id=session_id)
chat_service = ChatService()

def get_canvas_service() -> CanvasService:
return canvas_service

def get_chat_service() -> ChatService:
return chat_service

返回类实例时 Annotated[ChatService, 注解 如何注解 ChatService() 还是 ChatService 从原理上讲清楚


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

…annotations

Co-authored-by: wwfyde <17171720+wwfyde@users.noreply.github.com>
Copilot AI changed the title [WIP] Update chat session retrieval method Document type annotation principles for FastAPI dependency injection Nov 7, 2025
Copilot AI requested a review from wwfyde November 7, 2025 02:26
Copilot finished work on behalf of wwfyde November 7, 2025 02:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants