Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injection to Annotated on FastAPI Router (python 3.11) #767

Open
Modif93 opened this issue Nov 21, 2023 · 2 comments
Open

Injection to Annotated on FastAPI Router (python 3.11) #767

Modif93 opened this issue Nov 21, 2023 · 2 comments

Comments

@Modif93
Copy link

Modif93 commented Nov 21, 2023

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
Copy link
Author

Modif93 commented Nov 21, 2023

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.

@maintain0404
Copy link

maintain0404 commented Dec 3, 2023

#721 Use this.

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

No branches or pull requests

2 participants