From 40ae52223195898ffdf6b166ef850b41e3ec6384 Mon Sep 17 00:00:00 2001 From: Roman Mogylatov Date: Sat, 9 Jan 2021 08:54:24 -0500 Subject: [PATCH] Add providers async injections example --- docs/providers/async.rst | 5 +++++ examples/providers/async.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 examples/providers/async.py diff --git a/docs/providers/async.rst b/docs/providers/async.rst index b97121e5..39c79292 100644 --- a/docs/providers/async.rst +++ b/docs/providers/async.rst @@ -10,3 +10,8 @@ Asynchronous injections demonstrates how make asynchronous dependency injections in Python. Providers support asynchronous injections. + +.. literalinclude:: ../../examples/providers/async.py + :language: python + :emphasize-lines: 26-29 + :lines: 3- diff --git a/examples/providers/async.py b/examples/providers/async.py new file mode 100644 index 00000000..297b3b2f --- /dev/null +++ b/examples/providers/async.py @@ -0,0 +1,37 @@ +"""Asynchronous injections example.""" + +import asyncio + +from dependency_injector import containers, providers + + +async def init_async_resource(): + await asyncio.sleep(0.1) + yield 'Initialized' + + +class Service: + def __init__(self, resource): + self.resource = resource + + +class Container(containers.DeclarativeContainer): + + resource = providers.Resource(init_async_resource) + + service = providers.Factory( + Service, + resource=resource, + ) + + +async def main(container: Container): + resource = await container.resource() + service = await container.service() + ... + + +if __name__ == '__main__': + container = Container() + + asyncio.run(main(container))