python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Injection to Annotated on FastAPI Router (python 3.11)

Open Modif93 opened this issue 2 years ago • 2 comments

I'm using Dependency injector on my FastAPI Project.

currently using FastAPI

while Injecting some packages on FastAPI + SQLAlchemy + DI Project, for example

@router.get("/users")
@inject
def get_users(
        user_service: UserService = Depends(Provide[Container.user_service])
) -> List[UserModel] :
    some..codes..

I inject dependencies with non-annotated style codes.

can I do it with annotated style, like for example

userService = Annotated[UserService, Depends(Provide[Container.user_service])]

@router.get("/users")
@inject
def get_users(user_service: userService) -> List[UserModel] :
    some..codes..

It doesn't works well, with following errors.

AttributeError: 'Provide' object has no attribute 'get_all'

Think it finds dependency from Provide.

is there any way to use annotated style like above?

Modif93 avatar Nov 21 '23 08:11 Modif93

Ok, I'm answering my own question


@inject
def get_user_service(
        user_service: UserService = Depends(Provide[Container.user_service])
):
    return user_service

userService = Annotated[UserService, Depends(get_user_service)]

@router.get("/users")
def get_users(user_service: userService) -> List[UserModel] :
    some..codes..

working well with code above, and tried below,

@inject
def get_user_service(
        user_service: Annotated[UserService, Depends(Provide[Container.user_service])]
):
    return user_service

userService = Annotated[UserService, Depends(get_user_service)]

@router.get("/users")
def get_users(user_service: userService) -> List[UserModel] :
    some..codes..

same error. seems new wiring layer is needed for injection, between endpoint layer and service layer.

Modif93 avatar Nov 21 '23 08:11 Modif93

#721 Use this.

maintain0404 avatar Dec 03 '23 20:12 maintain0404