Skip to content
Merged
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
11 changes: 2 additions & 9 deletions cq/_core/routing/di.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@

from abc import abstractmethod
from collections.abc import Awaitable, Callable
from contextlib import nullcontext
from typing import TYPE_CHECKING, Any, Concatenate, Protocol, runtime_checkable

from cq.middlewares.contextlib import AsyncContextManagerMiddleware

if TYPE_CHECKING: # pragma: no cover
from cq import Command, CommandBus, EventBus, Middleware, QueryBus

Expand All @@ -23,8 +20,7 @@ class DIAdapter(Protocol):

__slots__ = ()

@abstractmethod
def command_scope(self) -> Middleware[Concatenate[Command, ...], Any]:
def command_scope(self) -> Middleware[Concatenate[Command, ...], Any] | None:
"""
Return a middleware that wraps each command dispatch.

Expand All @@ -39,7 +35,7 @@ def command_scope(self) -> Middleware[Concatenate[Command, ...], Any]:
instead of writing the middleware by hand.
"""

raise NotImplementedError
return None

@abstractmethod
def lazy[T](self, tp: type[T]) -> Callable[[], Awaitable[T]]:
Expand Down Expand Up @@ -88,9 +84,6 @@ def wire[T](self, tp: type[T]) -> Callable[..., Awaitable[T]]:
class NoDI(DIAdapter):
__slots__ = ()

def command_scope(self) -> Middleware[Concatenate[Command, ...], Any]:
return AsyncContextManagerMiddleware(nullcontext())

def lazy[T](self, tp: type[T], /) -> Callable[[], Awaitable[T]]:
tp_str = getattr(tp, "__name__", str(tp))
raise RuntimeError(
Expand Down
6 changes: 5 additions & 1 deletion cq/_core/routing/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ def query_types(self) -> KeysView[type[Query]]:

def new_command_bus(self) -> Bus[Command, Any]:
bus = SimpleBus(self.__command_registry)
bus.add_middlewares(self.__di.command_scope())

command_scope_middleware = self.__di.command_scope()
if command_scope_middleware is not None:
bus.add_middlewares(command_scope_middleware)

return bus

def new_event_bus(self) -> Bus[Event, None]:
Expand Down