Skip to content

Ressource not closed in case of Exception in the function #681

@BaptisteSaves

Description

@BaptisteSaves

Hello,

We have some function that uses Closing[Provide["session"]] to inject the database session to the method.
It works well, except if we have any exception raised in the function the closing method will not be called and the resource will stay open

This is really easy to reproduce with a minimal case on fastAPI, the shudown (db.close()) is never called in this case.

This is a huge problem as in the next call, the injector will re inject the resource (the session) which is already in a fail state.

I did not find anything on the documentation regarding error management, did we miss something ?

Thanks for your help.

Container

class Container(containers.DeclarativeContainer):
    wiring_config = containers.WiringConfiguration(packages=[XX])

    session = providers.Resource(get_db)

Resource DB:

def get_db() -> Iterator[Session]:
    db: Session = SessionMaker()
    try:
        yield db
    finally:
        db.close()

Router:

@router.get(
    "/hello-world"
)
@inject
async def hello_world(
    session: Session = Depends(Closing[Provide["session"]]),
):
    raise Exception()

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