python-dependency-injector/tests/unit/samples/wiring/asyncinjections.py
2025-10-24 13:27:57 +04:00

73 lines
2.0 KiB
Python

import asyncio
from typing_extensions import Annotated
from dependency_injector import containers, providers
from dependency_injector.wiring import Closing, Provide, inject
class TestResource:
def __init__(self):
self.init_counter = 0
self.shutdown_counter = 0
def reset_counters(self):
self.init_counter = 0
self.shutdown_counter = 0
resource1 = TestResource()
resource2 = TestResource()
resource3 = TestResource()
async def async_resource(resource):
await asyncio.sleep(0.001)
resource.init_counter += 1
yield resource
await asyncio.sleep(0.001)
resource.shutdown_counter += 1
class Container(containers.DeclarativeContainer):
resource1 = providers.Resource(async_resource, providers.Object(resource1))
resource2 = providers.Resource(async_resource, providers.Object(resource2))
context_local_resource = providers.ContextLocalResource(async_resource, providers.Object(resource3))
context_local_resource_with_factory_object = providers.ContextLocalResource(async_resource, providers.Factory(TestResource))
@inject
async def async_injection(
resource1: object = Provide[Container.resource1],
resource2: object = Provide[Container.resource2],
):
return resource1, resource2
@inject
async def async_generator_injection(
resource1: object = Provide[Container.resource1],
resource2: object = Closing[Provide[Container.resource2]],
):
yield resource1
yield resource2
@inject
async def async_injection_with_closing(
resource1: object = Closing[Provide[Container.resource1]],
resource2: object = Closing[Provide[Container.resource2]],
context_local_resource: object = Closing[Provide[Container.context_local_resource]],
):
return resource1, resource2, context_local_resource
@inject
async def async_injection_with_closing_context_local_resources(
context_local_resource1: object = Closing[Provide[Container.context_local_resource_with_factory_object]],
):
return context_local_resource1