Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/core/di/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ async def dispose(self) -> None:
if hasattr(instance, "__aenter__") and hasattr(instance, "__aexit__"):
await instance.__aexit__(None, None, None)
elif hasattr(instance, "dispose") and callable(instance.dispose):
instance.dispose()
result = instance.dispose()
if inspect.isawaitable(result):
await result

self._instances.clear()

Expand Down
31 changes: 31 additions & 0 deletions tests/unit/core/di/test_service_scope_dispose.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from __future__ import annotations

import pytest
from src.core.di.container import ServiceCollection


class _AsyncDisposable:
def __init__(self) -> None:
self.disposed = False

async def dispose(self) -> None:
self.disposed = True


@pytest.mark.asyncio
async def test_scope_dispose_awaits_async_dispose() -> None:
services = ServiceCollection()
services.add_scoped(
_AsyncDisposable,
implementation_factory=lambda _provider: _AsyncDisposable(),
)

provider = services.build_service_provider()
scope = provider.create_scope()

service = scope.service_provider.get_required_service(_AsyncDisposable)
assert service.disposed is False

await scope.dispose()

assert service.disposed is True
Loading