mirror of
https://github.com/ets-labs/python-dependency-injector.git
synced 2025-02-27 09:00:38 +03:00
Add providers async injections example
This commit is contained in:
parent
7f59ec25bd
commit
40ae522231
|
@ -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-
|
||||
|
|
37
examples/providers/async.py
Normal file
37
examples/providers/async.py
Normal 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))
|
Loading…
Reference in New Issue
Block a user