Skip to content

Commit

Permalink
Add async injections docs for wiring
Browse files Browse the repository at this point in the history
  • Loading branch information
rmk135 committed Jan 9, 2021
1 parent 7326304 commit 74149e8
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions docs/wiring.rst
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,75 @@ You can use that in testing to re-create and re-wire a container before each tes
module.fn()
Asynchronous injections
-----------------------

Wiring feature supports asynchronous injections:

.. code-block:: python
class Container(containers.DeclarativeContainer):
db = providers.Resource(init_async_db_client)
cache = providers.Resource(init_async_cache_client)
@inject
async def main(
db: Database = Provide[Container.db],
cache: Cache = Provide[Container.cache],
):
...
Wiring prepares injections asynchronously. Here is what it does for previous example:

.. code-block:: python
db, cache = await asyncio.gather(
container.db(),
container.cache(),
)
await main(db=db, cache=cache)
You can also use ``Closing`` marker with the asynchronous ``Resource`` providers:

.. code-block:: python
@inject
async def main(
db: Database = Closing[Provide[Container.db]],
cache: Cache = Closing[Provide[Container.cache]],
):
...
Wiring does closing asynchronously:

.. code-block:: python
db, cache = await asyncio.gather(
container.db(),
container.cache(),
)
await main(db=db, cache=cache)
await asyncio.gather(
container.db.shutdown(),
container.cache.shutdown(),
)
See :ref:`Resources, wiring and per-function execution scope <resource-provider-wiring-closing>` for
details on ``Closing`` marker.

.. note::

Wiring does not not convert asynchronous injections to synchronous.

It handles asynchronous injections only for ``async def`` functions. Asynchronous injections into
synchronous ``def`` function still work, but you need to take care of awaitables by your own.

Integration with other frameworks
---------------------------------

Expand Down

0 comments on commit 74149e8

Please sign in to comment.