Add providers async injections example

This commit is contained in:
Roman Mogylatov 2021-01-09 08:54:24 -05:00
parent 7f59ec25bd
commit 40ae522231
2 changed files with 42 additions and 0 deletions

View File

@ -10,3 +10,8 @@ Asynchronous injections
demonstrates how make asynchronous dependency injections in Python. demonstrates how make asynchronous dependency injections in Python.
Providers support asynchronous injections. Providers support asynchronous injections.
.. literalinclude:: ../../examples/providers/async.py
:language: python
:emphasize-lines: 26-29
:lines: 3-

View File

@ -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))