Skip to content

[Feature Request] Support Generator-Based Providers / Scoped Dependencies #70

Description

@1owkeyme

Problem Statement

It would be great to have finalization support for injected dependencies, eliminating the need for factory boilerplate in handlers.

Current Situation

# Define factory interface
class IUowFactory(Protocol):
    def __call__(self) -> AsyncContextManager[IUoW]: ...

# Handler receives factory, not UoW
class CancelTaskCommandHandler(cqrs.RequestHandler[...]):
    def __init__(self, uow_factory: IUowFactory) -> None:
        self._uow_factory = uow_factory
    
    async def handle(self, command: ...) -> ...:
        # Manual context management in EVERY handler
        async with self._uow_factory() as uow:
            # Actual business logic
            result = await uow.tasks.cancel(command.task_id)
            await uow.commit()
            return result

Problems:

  • Factory boilerplate in every handler
  • Manual async with management
  • Error-prone cleanup
  • Harder to test (mock factory + context)
  • Violates DRY

Desired Situation

from dishka import Provider, Scope, provide

class UoWProvider(Provider):
    @provide(scope=Scope.REQUEST)
    def provide_uow(self) -> AsyncGenerator[IUoW, None]:
        async with create_uow() as uow:  # Generator handles lifecycle!
            yield uow
            # Auto-cleanup after scope ends

# Handler gets UoW directly!
class CancelTaskCommandHandler(cqrs.RequestHandler[...]):
    def __init__(self, uow: IUoW) -> None:  # Direct injection
        self._uow = uow
    
    async def handle(self, command: ...) -> ...:
        # Just use uow, lifecycle managed by DI
        result = await self._uow.tasks.cancel(command.task_id)
        await self._uow.commit()
        return result

Benefits:

  • Clean handler signatures
  • Automatic lifecycle management
  • Guaranteed resource cleanup
  • Easy testing (just mock UoW)
  • Single source of truth for resource setup/teardown

Why matters

Other DI libraries (Dishka, FastAPI DI) solve this elegantly with generator providers. Without this, every handler in our codebase (50+ handlers) repeats the same boilerplate, increasing maintenance burden and risk of cleanup bugs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions