Skip to content

Async providers with async dependencies #368

@kolypto

Description

@kolypto

It turns out that async providers currently cannot have async dependencies.

Example: in this container, both are async functions:

class Container(containers.DeclarativeContainer):
    db = providers.Factory(async_db_provider)
    service = providers.Singleton(async_service, db=db)

Now, when in my code I request an instance of service:

service = await container.service()

the expected result would be an instance of service. The actual result is its unawaited coroutine:

<coroutine object async_service at 0x7faea530fc40>

This behavior persists with Resource, Couroutine, and other providers.


Full source code to reproduce:

# Create two async providers

async def async_db_provider():
    return {'db': 'ok'}  # just some sample object

async def async_service(db = None):
    return {'service': 'ok', 'db': db}


class Container(containers.DeclarativeContainer):
    # Second provider, a singleton, depends on the first one
    db = providers.Factory(async_db_provider)
    service = providers.Singleton(async_service, db=db)


if __name__ == '__main__':
    # Create the container
    container = Container()

    async def main():
        try:
            # Request the service
            service = await container.service()
            print(service)  # <--- expected: instance of service
        finally:
            # Shutdown resources
            shutdown_resources_awaitable = container.shutdown_resources()
            if isawaitable(shutdown_resources_awaitable):
                await shutdown_resources_awaitable

    asyncio.run(main())

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions