Skip to content

@inject isn't woking at FastAPI #938

@fbuccioni

Description

@fbuccioni

Hi, I'm trying to implement the dependency injection in FastAPI routes but I didn't make it work, here is a Reproducible Minimal Example.

from typing import Annotated
from dependency_injector import containers, providers
from dependency_injector.providers import Factory
from dependency_injector.wiring import Provide, inject
from fastapi import FastAPI, Depends
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

# Service
class ChatService:
    """Minimal chat service with dependencies"""
    def __init__(
        self,
        user: str,
        predefined_param: int
    ):
        self.user = user
    
    async def send_message(self):
        yield "message"

# Contaienr
class ChatContainer(containers.DeclarativeContainer):
    # Chat service factory with dependencies
    chat_service = providers.Factory(
        ChatService, predefined_param=10
    )


# Input model
# Pydantic model for request
class ChatMessage(BaseModel):
    content: str


# FastAPI magic
app = FastAPI(title="Minimal DI Example")

@app.post("/chat/stream")
@inject
async def stream_chat(
    message: ChatMessage,
    chat_service_factory: Annotated[
        Factory[ChatService],
        Depends(Provide[ChatContainer.chat_service.provider])
    ]
):
    chat_service = chat_service_factory(
        user="TestUser",
    )
    
    return StreamingResponse(
        chat_service.send_message(),
        media_type="text/plain"
    )

# RUN!!
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

And it is tested with

curl -v http://0.0.0.0:8000/chat/stream -H 'Content-type: application/json' -d '{"content":"hola"}'

I can do a workaround by using

 chat_service_factory:  Factory[ChatService] = Depends(lambda: ChatContainer.chat_service)

But I want to use the proper types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions