From e915a09f5747e9a7a594c89b2650adb58a380980 Mon Sep 17 00:00:00 2001 From: remimd Date: Sun, 30 Aug 2026 14:44:11 +0200 Subject: [PATCH] refactor: Make command_scope optional --- cq/_core/routing/di.py | 11 ++--------- cq/_core/routing/router.py | 6 +++++- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/cq/_core/routing/di.py b/cq/_core/routing/di.py index 51fb4ac..dc13d93 100644 --- a/cq/_core/routing/di.py +++ b/cq/_core/routing/di.py @@ -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 @@ -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. @@ -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]]: @@ -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( diff --git a/cq/_core/routing/router.py b/cq/_core/routing/router.py index ea9d2a3..fe7cac5 100644 --- a/cq/_core/routing/router.py +++ b/cq/_core/routing/router.py @@ -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]: