Onboarding guide
5. CQRS: Commands, Queries & the Decorator Pipeline
What this group covers. Every write and every read in an MMCA application is a use case: a small, single-purpose object (a command or a query) handed to a handler that does exactly one thing. This group is the framework's implementation of CQRS (Command/Query Responsibility Segregation), the cross-cutting pipeline wrapped around it, and the generic write side that saves a module from hand-writing the same create/update/delete handler for every aggregate. There are six families:
- The two handler contracts,
ICommandHandler<in TCommand, TResult>andIQueryHandler<in TQuery, TResult>, plus the payload markers that describe a use case's shape:ICommandWithRequest<out TRequest>(a command that embeds a request DTO) andICreateRequest(the constraint that ties a create DTO to its mapper). - The decorator pipeline: eight command decorators
(
ViewAsCommandDecorator<TCommand, TResult>,FeatureGateCommandDecorator<TCommand, TResult>,AuthorizationCommandDecorator<TCommand, TResult>,LoggingCommandDecorator<TCommand, TResult>,CachingCommandDecorator<TCommand, TResult>,ValidatingCommandDecorator<TCommand, TResult>,TimeoutCommandDecorator<TCommand, TResult>,TransactionalCommandDecorator<TCommand, TResult>), six query decorators (FeatureGateQueryDecorator<TQuery, TResult>,AuthorizationQueryDecorator<TQuery, TResult>,LoggingQueryDecorator<TQuery, TResult>,CachingQueryDecorator<TQuery, TResult>,ValidatingQueryDecorator<TQuery, TResult>,TimeoutQueryDecorator<TQuery, TResult>), an optional profiling pair (ProfilingCommandDecorator<TCommand, TResult>,ProfilingQueryDecorator<TQuery, TResult>), and the helpers they lean on: the failure buildersResultFailureFactoryandResultFailure<TResult>,CqrsMetrics, the four shared decisions that keep each command/query twin from drifting (FeatureFlagGate,AuthorizationGate,ValidationGate(with its per-type request probeRequestShape<T>) andTimeoutBudget), the two cache-key scopersTenantCacheKeyandUserCacheKey, the reserved cross-service key segmentCrossServiceCacheKeys, and the stampede lock tableQueryCacheKeyLocks. - The opt-in marker interfaces that let one use case switch one concern on:
ITransactional,ICacheInvalidating(with its prefix builderEntityCachePrefix),IQueryCacheable,IFeatureGated,IRequiresPermissionandIHasTimeout, plus the one opt-out marker,ISharedQueryCache. - The generic write side: the load-mutate-save core
MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType>with its per-run side channelMutationContext, the three result shapes built on it (MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType>, its DTO-returning sibling, andMutateEntityPayloadHandlerBase<TCommand, TEntity, TIdentifierType, TResultPayload>), the create workflow (CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>and its hook-free floorCreateEntityHandler<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>), the update and delete pairs (UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType>,UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>,UpdateEntityCommandHandler<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>,DeleteEntityCommand<TEntity, TIdentifierType>,DeleteEntityHandler<TEntity, TIdentifierType>), the child-collection pair (AddChildEntityHandlerBase<TCommand, TParent, TIdentifierType, TChild, TChildDTO>,RemoveChildEntityHandlerBase<TCommand, TParent, TIdentifierType>), and the two applier contracts that keep field names out of the framework (IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>,IEntityUpdateCommandApplier<TEntity, TUpdateRequest, TIdentifierType, in TCommand>). - The declared-contract markers and their inspector:
ICommand<TResult>andIQuery<TResult>, read byCqrsContractInspector, which reports eachCqrsContractMismatchclassified byCqrsContractMismatchKind. - The Application-layer contracts that sit beside the pipeline, implemented in Infrastructure and
consumed by use cases:
ITenantContext(which tenant this scope runs as),IDistributedLock(mutual exclusion across replicas),ICounterStore(atomic fixed-window counters for throttles),IScheduledJob(recurring work on a cron schedule),IAuditTrailReader(the recorded change history of one entity),IAuditTrailWriter(records an event that changed no data on that trail),IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>(opt-in projection pushdown on list reads), the event-versioning pairIEventUpcaster/IEventUpcasterRegistry, the consumer-inbox stagerIInboxRecorder, and the coverage declaration a navigation populator makes,INavigationPopulatorCoverage.
This is the central column of [Rubric §6, CQRS & Event-Driven] (reads separated from writes,
intent-revealing use cases) and [Rubric §12, Performance & Scalability] (the place those concerns are
implemented once, uniformly, instead of scattered through handlers). The governing decision is
ADR-014, revised four times:
2026-07-19 for the transactional semantics, 2026-08-18 for the pipeline order (an Authorization
decorator between FeatureGate and Logging, a Timeout decorator between Validating and Transactional,
on both chains), 2026-08-26 for the query-side Validating decorator plus the sealed composition path,
and 2026-08-31 to correct the validator semantics. The command chain has since gained one more
outermost layer, the view-as guard of
ADR-137. The ADR's own Status block warns that the order
printed in its Decision section is the pre-2026-08-18 one and points at the later revisions, so read
the revisions, not the decision, when you need the current chain.
The shape: thin handlers, fat pipeline
A handler is deliberately tiny. ICommandHandler<in TCommand, TResult>
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommandHandler.cs:9) and
IQueryHandler<in TQuery, TResult>
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/IQueryHandler.cs:10) are one method each,
Task<TResult> HandleAsync(T, CancellationToken cancellationToken = default), with in
(contravariant) variance on the input (ICommandHandler.cs:17, IQueryHandler.cs:18). TResult is
almost always the Result or Result<T> of the
Result pattern
(ADR-013): a handler returns a failure
value, it does not throw for expected error paths. Commands mutate state; queries are
side-effect-free reads. Splitting the two into distinct interfaces is what lets the container apply a
different set of cross-cutting concerns to each (writes get a transaction, reads get result
caching), and it is the boundary [Rubric §1, SOLID] rewards: each handler has one reason to change,
and each decorator one responsibility.
Everything that is not the business logic of a use case lives outside the handler, in a stack of
decorators. A decorator implements the same handler interface, takes the next handler in through
its primary constructor (inner), does its cross-cutting job, and delegates. Because each decorator
is an ICommandHandler/IQueryHandler, they nest arbitrarily and the concrete handler at the
bottom never knows it is wrapped. This is the textbook Decorator pattern
([Rubric §2, Design Patterns]), applied at the application boundary so that logging, caching,
validation, feature flags, permission checks, execution budgets, and transactions are each written
once and reused by every handler in every module, and so that the same behavior applies whether the
call arrives over REST, gRPC, or an integration-event consumer.
How the pipeline is assembled (registration versus execution order)
The wiring lives in the partial DependencyInjection class
(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:31, with the module scan in
DependencyInjection.ModuleScanning.cs and the CRUD registrations in DependencyInjection.Crud.cs), exposed as
extension(IServiceCollection services) members (the C# extension(T) syntax,
primer §4). The sequence a host must follow is
strict and ordered:
AddApplication()(DependencyInjection.cs:39) registers the core singletons: the domain event dispatcher, the upcaster registry, the navigation metadata provider and theEntityQueryPipeline(DependencyInjection.cs:41,:47,:49-50), the no-op default navigation populator (DependencyInjection.cs:58), then Common's own validators (DependencyInjection.cs:70).ScanModuleApplicationServices<TAssemblyMarker>()(DependencyInjection.ModuleScanning.cs:29, delegating to theAssembly-typed overload atDependencyInjection.ModuleScanning.cs:47) runs once per module and uses the framework's own assembly-scanning helper,AddAssignableTypes, to register domain and integration event handlers (singleton,DependencyInjection.ModuleScanning.cs:52-56), DTO mappers, DTO projectors, request mappers and both update appliers (scoped,DependencyInjection.ModuleScanning.cs:58-76), and every concreteICommandHandler<,>/IQueryHandler<,>(scoped,DependencyInjection.ModuleScanning.cs:78-80), plus FluentValidation validators (DependencyInjection.ModuleScanning.cs:82).AddApplicationDecorators()(DependencyInjection.cs:145) is called last. It wraps the already-registered handlers throughTryDecorateWith, a linked internal helper rather than a third-party container extension (MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:115). This ordering is load-bearing: decoration can only wrap registrations that already exist, which is why decorators must come after every module's handler scan (DependencyInjection.cs:80-83).
The subtle rule is registration order versus execution order, and the code states it once so
nobody has to invert it in their head. Each pipeline is written outermost first, exactly as a
request travels through it (DependencyInjection.cs:85-87): the command list at
DependencyInjection.cs:168-178 and the query list at :181-189. A private helper,
DecorateInExecutionOrder (DependencyInjection.cs:403), walks each list backwards and applies the
innermost decorator first, because each decoration wraps the registration as it stands, so the last
one applied is the outermost at runtime (DependencyInjection.cs:399-409). The XML doc above the
method draws the resulting nesting (DependencyInjection.cs:90-101):
ViewAsCommandDecorator outermost (applied last)
-> FeatureGateCommandDecorator
-> AuthorizationCommandDecorator
-> LoggingCommandDecorator
-> CachingCommandDecorator
-> ValidatingCommandDecorator
-> TimeoutCommandDecorator
-> TransactionalCommandDecorator innermost (applied first)
-> ConcreteHandler the actual business logic
The query side (DependencyInjection.cs:181-189, drawn at DependencyInjection.cs:104-113) is the same
chain minus the view-as guard and the transaction: a view-as caller may read, and there is nothing to
commit on a read:
FeatureGateQueryDecorator
-> AuthorizationQueryDecorator
-> LoggingQueryDecorator
-> CachingQueryDecorator
-> ValidatingQueryDecorator
-> TimeoutQueryDecorator
-> ConcreteHandler
Caching is the one position that is not always present. It is a host opt-in: AddQueryCaching()
(DependencyInjection.cs:223) records a private marker (:227, the QueryCachingOptIn type at
:374) that AddApplicationDecorators() reads (DependencyInjection.cs:162-165). With it, the
caching pair takes its place between Logging and Validating on both lists
(DependencyInjection.cs:174, :186); without it, the pair is left out and every other position is
unchanged. In a host that never opted in, IQueryCacheable and ICacheInvalidating are inert
markers, so it pays no prefix eviction on writes against keys nothing populates
(DependencyInjection.cs:209-213). Because it is a flag read at decoration time, it must run before
the pipeline closes or inside the AddMmcaApplicationPipeline callback
(DependencyInjection.cs:216-218).
The order is pinned by a test, not only by the comments. DecoratorPipelineOrderTestsBase
(MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/DecoratorPipelineOrderTestsBase.cs:39) resolves both
handler types from a real ServiceCollection and unwraps the constructed object graph by reflection,
asserting the two sequences outermost-first (DecoratorPipelineOrderTestsBase.cs:89-94, comparison at
:110, with the final entry asserted not to be a decorator at DecoratorPipelineOrderTestsBase.cs:113).
Both expected lists are protected virtual (DecoratorPipelineOrderTestsBase.cs:62, :78) and carry
the caching pair only when the equally overridable UsesQueryCaching (default false, :56) says
the host opted in, so a consumer whose chain differs can override them; MMCA.Common subclasses the base against its own registration
sequence without overriding either list
(MMCA.Common/Tests/Hosting/MMCA.Common.Testing.Tests/Conformance/DecoratorPipelineOrderTests.cs:25, the real
registration sequence at DecoratorPipelineOrderTests.cs:45-51). That is [Rubric §14, Testability]
doing governance work: the diagram above cannot silently drift from the registrations below it.
Two later additions close the remaining hole, which was never the order but the timing. First, the
collection is sealed: AddApplicationDecorators() ends by adding a private marker type
(DependencyInjection.cs:191, SealPipeline at DependencyInjection.cs:411), and every registration
entry point that adds handlers or changes the chain (ScanModuleApplicationServices, AddEntityCrud,
AddEntityUpdateVerb, AddEntityUpdate, AddQueryCaching, AddMmcaApplicationPipeline) calls ThrowIfPipelineSealed
first, so a late module scan throws an InvalidOperationException that says exactly what went wrong
instead of silently producing an undecorated handler (DependencyInjection.cs:414-423). Second,
AddMmcaApplicationPipeline(...) (DependencyInjection.cs:284) runs the whole sequence in the one
order that works: AddApplication(), then the caller's registrations through an
MmcaApplicationPipelineBuilder,
then AddApplicationDecorators() (DependencyInjection.cs:286-292). Seven production service hosts
compose it that way through MMCA.Common.ServiceHost's AddMmcaServiceHost, which calls it with each
host's ConfigurePipeline callback
(MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:158; for example
MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:359 and
MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:106), and MMCA.Helpdesk's web
host calls it directly (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:138). Alongside it,
VerifyDecoratorPipeline() (DependencyInjection.cs:321) is a registration-shape assertion an
architecture fitness test can call: it never builds a provider. It first throws when the pipeline
was never closed at all (DependencyInjection.cs:323-328), then looks for a surviving non-keyed
descriptor that still carries an implementation type, which after decoration is proof that nothing
wrapped it (from DependencyInjection.cs:330). MMCA.Store's architecture tests call it
today (MMCA.Store/Tests/Architecture/MMCA.Store.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:68).
A separate, optional call layers MiniProfiler on top: AddApplicationProfiling()
(DependencyInjection.cs:237-241, one TryDecorateWith per handler kind at :239-240) registers
ProfilingCommandDecorator<TCommand, TResult>
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ProfilingCommandDecorator.cs:12,
one MiniProfiler.Current?.Step(...) around the inner call at ProfilingCommandDecorator.cs:18) and
its read twin ProfilingQueryDecorator<TQuery, TResult>
(.../Decorators/ProfilingQueryDecorator.cs:11, :17). The composed service host calls it after the
sealed pipeline when ApplicationSettings:UseMiniProfiler is true, which it is not by default
(MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:162-165), so
the profiling pair stays opt-in, switched by configuration
(ADR-014).
Why this exact order, and what each layer guards
The nesting order is a deliberate cost-and-correctness argument, spelled out in the registration
XML-doc (DependencyInjection.cs:116-142):
- The view-as guard is outermost on the command side, so a staff user viewing the app as another
user can read but never write in that user's name, and a refused command does no feature-flag
lookup, permission check, logging, validation or transaction work (
ViewAsCommandDecorator.cs:9-17, first in the outermost-first command list atDependencyInjection.cs:170).ViewAsCommandDecorator<TCommand, TResult>(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ViewAsCommandDecorator.cs:21) takes only the inner handler andICurrentUserService(ViewAsCommandDecorator.cs:21-23). For an ordinary caller it costs one claim lookup and passes straight through; for a principal that reportsIsViewAs()it returnsError.Forbiddenwith the codeAuth.ViewAsReadOnlywithout invoking the handler (ViewAsCommandDecorator.cs:28-33). It is the second layer behind the HTTP layer's own refusal of non-safe methods for such a caller, and the one that also covers a command sent from a GET handler or a hub method (ViewAsCommandDecorator.cs:9-12, ADR-137). There is no query twin: reading is exactly what a view-as session is for. - Feature-gating is outermost on queries and sits directly inside the view-as guard on commands,
so a disabled feature is rejected with zero downstream work: no permission check, no log scope,
no cache touch, no validation, no budget, no transaction (
DependencyInjection.cs:118-122).FeatureGateCommandDecorator<TCommand, TResult>(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/FeatureGateCommandDecorator.cs:21) and its read twinFeatureGateQueryDecorator<TQuery, TResult>(.../Decorators/FeatureGateQueryDecorator.cs:20) are each one call into the shared decisionFeatureFlagGate(.../Decorators/FeatureFlagGate.cs:12, called atFeatureGateCommandDecorator.cs:28andFeatureGateQueryDecorator.cs:27), which callsIFeatureManager.IsEnabledAsynconly when the use case opts in viaIFeatureGated(FeatureFlagGate.cs:23-27) and otherwise returns aNotFounderror carrying the codeFeature.Disabled(FeatureFlagGate.cs:32-34); the decorator turns that error into theTResultfailure (FeatureGateCommandDecorator.cs:29-31,FeatureGateQueryDecorator.cs:28-30). The message is the same generic wording the HTTP-level[FeatureGate]refusal uses, and the flag name stays out of it because it reaches the user verbatim (FeatureFlagGate.cs:29-31). A disabled feature reads as "this does not exist" rather than "you may not", which is the deliberate posture of ADR-031, and it is also why the gate stays outside authorization: an off feature must answer identically for every caller instead of leaking which permission guards it (DependencyInjection.cs:118-122). - Authorization sits directly inside the gate and outside caching, so a denied request neither
reads nor populates the cache (
DependencyInjection.cs:123-125).AuthorizationCommandDecorator<TCommand, TResult>(.../Decorators/AuthorizationCommandDecorator.cs:28) andAuthorizationQueryDecorator<TQuery, TResult>(.../Decorators/AuthorizationQueryDecorator.cs:23) takeICurrentUserServiceandIPermissionRegistry, and bothHandleAsyncbodies are three lines over one shared decision,AuthorizationGate(.../Decorators/AuthorizationGate.cs:18, called atAuthorizationCommandDecorator.cs:36andAuthorizationQueryDecorator.cs:31): the gate returnsnullwhen the request may run, or theForbiddenErrorto short-circuit with (AuthorizationGate.cs:27-31,:57), and the decorator shapes that error into aTResultfailure without invoking the handler (AuthorizationCommandDecorator.cs:37-40,AuthorizationQueryDecorator.cs:32-35). Factoring the decision out is the point: the two decorators differ only in which generic parameter names the request, and a rule enforced on commands but not on queries reads as working until someone moves a use case from one to the other (AuthorizationGate.cs:13-17). The gate runs one check, the capability check: it fires for a request that implementsIRequiresPermissionand grants on either source, a role the host's registry maps to the permission or a permission claim carried on the principal itself (AuthorizationGate.cs:45-47); checking the registry alone would deny in one service what the endpoint policy allows in another, since only the minting host reads the grant table (AuthorizationGate.cs:32-37). A denial isError.Forbiddenwith the codeAuthorization.PermissionDenied(AuthorizationGate.cs:51-54), counted onCqrsMetricsinside the gate so a decorator only has to shape the failure (AuthorizationGate.cs:49,:28-30). Both decorators are registered unconditionally and both take anIPermissionRegistry, soAddApplicationDecorators()TryAddsUnconfiguredPermissionRegistryfirst (DependencyInjection.cs:154): a host that declared its own grants keeps its registry, and a host with no permission model still resolves every handler. This is defense in depth beside the endpoint's[Authorize]policy rather than a replacement for it: the capability check travels with the use case, so a command reached over gRPC, from a scheduled job, or from another module is checked the same way it is over HTTP. That is[Rubric §11, Security]moving inward, and it is the pipeline-side surface of ADR-020. - Logging sits just inside authorization so it measures only enabled, permitted executions
(
DependencyInjection.cs:126).LoggingCommandDecorator<TCommand, TResult>(.../Decorators/LoggingCommandDecorator.cs:18) opens a source-generated structured-logging scope carrying the command name, the owning module and theCorrelationIdfromICorrelationContext(LoggingCommandDecorator.cs:33, scope shape atLoggingCommandDecorator.cs:98-100), and publishes the same name as the ambient query tag, so the SQL the handler emits several awaits later names this use case in a query store (QueryTagScope.BeginatLoggingCommandDecorator.cs:32, rationale at:29-31). The module name is derived once per closed generic type throughModuleNameConventions, so every log line a handler emits can be filtered by module without paying for a namespace parse per execution (LoggingCommandDecorator.cs:107). It times the whole inner pipeline withStopwatch.GetTimestamp()/Stopwatch.GetElapsedTimerather than aStopwatchinstance (one fewer allocation per command,LoggingCommandDecorator.cs:40,:44), and separates four outcomes:completed(Information),failed(aResultin a failure state, Warning with an error summary),cancelled(Debug, then rethrown) andexception(Warning, then rethrown), atLoggingCommandDecorator.cs:46-90with the levels declared atLoggingCommandDecorator.cs:117-134.cancelledcovers only anOperationCanceledExceptionraised while the caller's own token is cancelled (a client disconnect, a host shutdown): that is routine traffic rather than a failure of the command, so it does not inflate the exception outcome, while a timeout budget's own expiry is not the caller's token and still lands inexception(LoggingCommandDecorator.cs:60-70, level rationale at:132). The exception branch logs the outcome line without the exception object, because the boundary that finally handles it (the global exception handler, or the internal-command processor for a deferred command) logs it once at Error with its full stack: logging it here too would produce two Error rows and two stacks for every unhandled exception, and the correlation id is what joins this line to that stack (LoggingCommandDecorator.cs:75-81). Each outcome is also recorded to theCqrsMetricsduration histogram taggedcommandandoutcome(LoggingCommandDecorator.cs:109-113). This is the RED (Rate, Errors, Duration) anchor of[Rubric §13, Observability & Operability](ADR-041). The read sideLoggingQueryDecorator<TQuery, TResult>(.../Decorators/LoggingQueryDecorator.cs:16) is the same shape, query tag and all (LoggingQueryDecorator.cs:30-31) and the same four outcomes includingcancelled(LoggingQueryDecorator.cs:56-66), againstCqrsMetrics.QueryDuration(LoggingQueryDecorator.cs:103), with one calibration difference: a completed query logs at Debug rather than Information (LoggingQueryDecorator.cs:108), because reads are the high-volume half. - Cache invalidation sits outside validation and outside the transaction, so the cache is only
cleared after a valid, committed mutation (
DependencyInjection.cs:132-133).CachingCommandDecorator<TCommand, TResult>(.../Decorators/CachingCommandDecorator.cs:43) callsICacheService.RemoveByPrefixAsynconly when the command opts in viaICacheInvalidatingand its prefix is non-blank (CachingCommandDecorator.cs:98-102). A failure result skips the eviction, because it persisted nothing and must not evict valid entries (CachingCommandDecorator.cs:80-85); a handler that throws still evicts before the exception is rethrown unchanged, because the write may already have committed (a post-save hook that threw on a command that is notITransactional), and after a rollback the extra eviction costs only a cache miss (CachingCommandDecorator.cs:71-78). Three details there are worth memorizing: the blank-prefix guard is the opt-out and a safety catch, sinceRemoveByPrefixAsync("")would evict the entire cache (CachingCommandDecorator.cs:96-99); the eviction runs withCancellationToken.Noneand swallows a runtime fault into a warning, because the command may already have committed and a cache outage must not turn a committed write into a failure (CachingCommandDecorator.cs:110-113,:123-128), while anArgumentException(a prefix that does not end at the:boundaryRemoveByPrefixAsyncrequires) is a bug in the command, logged at Error and not retried because a second attempt would fail identically (CachingCommandDecorator.cs:115-122, contract atICacheInvalidating.cs:15-21); and otherwise a second, delayed eviction fires afterReInvalidationDelay(5 seconds by default,CachingCommandDecorator.cs:55) to remove an entry that an in-flight read repopulated with pre-write state, scheduled even when the first eviction failed so a transient fault gets its retry (CachingCommandDecorator.cs:130-136,:143-156). That follow-up task is held on an internal property rather than dropped, so it is observed and a test can await it deterministically (CachingCommandDecorator.cs:61). On the read side,CachingQueryDecorator<TQuery, TResult>(.../Decorators/CachingQueryDecorator.cs:43) computes the effective key once, scoped to the caller and then to the tenant (CachingQueryDecorator.cs:58-59, covered below), serves hits without touching the handler (CachingQueryDecorator.cs:74-79), stores only non-failure results (CachingQueryDecorator.cs:115-132), and is fail-open throughout: a failed read is logged and treated as a miss, a failed populate returns the answer uncached, and onlyOperationCanceledExceptionescapes either guard (CachingQueryDecorator.cs:125,:234-238). A value-typeTResultreads throughTryGetAsync, becauseGetAsyncanswers a miss withdefault(TResult), which for aboolor anintis nevernulland would be served as a hit (CachingQueryDecorator.cs:205-211,:224-232). Both halves are the pipeline's[Rubric §12, Performance & Scalability]story (ADR-026). - Validation sits outside the budget and, on the write side, outside the transaction, so a
malformed command never spends its timeout allowance or opens a database transaction
(
DependencyInjection.cs:127-131).ValidatingCommandDecorator<TCommand, TResult>(.../Decorators/ValidatingCommandDecorator.cs:31) materializesIEnumerable<IValidator<TCommand>>into an array (ValidatingCommandDecorator.cs:36), passes straight through when it is empty (ValidatingCommandDecorator.cs:41-44), and otherwise hands the array to the shared passValidationGate(.../Decorators/ValidationGate.cs:12, called atValidatingCommandDecorator.cs:46), which runs every registered validator sequentially and unions their failures (ValidationGate.cs:30-46); a non-null error list becomes a typed failure without ever calling the handler (ValidatingCommandDecorator.cs:47-53). Running them all rather than only the first is deliberate: a command commonly carries a module-authored validator beside a framework one, and honoring only the first turns the others into silently unenforced rules (ValidatingCommandDecorator.cs:18-21); the loop is sequential because a validator may read through a scoped repository and aDbContextis not thread-safe (ValidationGate.cs:27-29).ValidatingQueryDecorator<TQuery, TResult>(.../Decorators/ValidatingQueryDecorator.cs:34) is the same shape over the same gate (ValidatingQueryDecorator.cs:42-57), so a query carrying paging, filter or sort input rejects a malformed request instead of pushing bad values into the data source. It sits inside caching on purpose: a cached entry can only exist because the same query already passed validation when the entry was produced, so re-validating on a hit spends work to reach a conclusion already reached (ValidatingQueryDecorator.cs:21-29). Commands that embed a request DTO viaICommandWithRequest<out TRequest>get a validator wired automatically: the module scan reflects over the assembly andTryAdds aCommandRequestValidator<TCommand, TRequest>for each (DependencyInjection.ModuleScanning.cs:86-100), withTryAddsemantics so an explicitIValidator<TCommand>always wins (DependencyInjection.ModuleScanning.cs:84-85), andAddCommandRequestValidator<TCommand, TRequest>()(DependencyInjection.Crud.cs:220-223) is the explicit form for a closed generic command the scan cannot see. That whole story belongs to G06, Validation ([Rubric §24, Forms, Validation & UX Safety]). - The timeout budget sits inside validation and outside the transaction, so it covers the database
work that actually hangs, does not charge the caller for validation, and cancels the transaction
rather than leaving it open (
DependencyInjection.cs:134-137).TimeoutCommandDecorator<TCommand, TResult>(.../Decorators/TimeoutCommandDecorator.cs:34) is a single expression that hands the command to the shared budgetTimeoutBudget(.../Decorators/TimeoutBudget.cs:11, called atTimeoutCommandDecorator.cs:38-39). The budget passes through unless the request implementsIHasTimeoutwith a positive budget (TimeoutBudget.cs:35-36), otherwise links a freshCancellationTokenSourceto the caller's token and callsCancelAfter(TimeoutBudget.cs:38-39). Thewhenclause on the catch is the whole design: only a cancellation raised by the budget's own source, with the caller's token still un-cancelled, becomes a failure result (TimeoutBudget.cs:45), so a genuinely aborted request still surfaces exactly as the inner handler would. An expired budget is reported asError.Unavailable("Request.TimedOut", ...)(TimeoutBudget.cs:50-55): the work (usually a dependency such as the database) did not answer in time, which is not the request's fault, so it is HTTP 503 at the edge and a caller may retry later, while the machine-readable code tells a timeout apart from other outages (TimeoutCommandDecorator.cs:14-17). The expiry is also counted onCqrsMetrics(TimeoutBudget.cs:48). The read twinTimeoutQueryDecorator<TQuery, TResult>(.../Decorators/TimeoutQueryDecorator.cs:34) is the same one call with"query"in place of"command"(TimeoutQueryDecorator.cs:38-39) but sits innermost on the query side, so a cache hit is served without starting a budget at all (TimeoutQueryDecorator.cs:20-22). This is[Rubric §29, Resilience & Business Continuity]expressed per use case rather than per host. - Transaction is innermost (closest to the handler) so the unit-of-work boundary is as tight as
possible.
TransactionalCommandDecorator<TCommand, TResult>(.../Decorators/TransactionalCommandDecorator.cs:18) is sixteen lines (18-33): pass through unless the command implementsITransactional(TransactionalCommandDecorator.cs:26-27), otherwise hand the inner call toIUnitOfWork.ExecuteInTransactionAsync(TransactionalCommandDecorator.cs:29-31). Everything interesting happens on the other side of that call, inDbContextFactory([Rubric §8, Data Architecture]), and it is worth reading: a returned failedResultrolls the transaction back, exactly like an exception (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:643-649); the call is re-entrant, so a nested transaction joins the ambient one and only the outermost call begins, commits, or rolls back (DbContextFactory.cs:590-591); in-process domain event dispatch is deferred until after a successful commit and dropped on rollback (DbContextFactory.cs:666-671); and a failure of the commit itself is never retried, surfacing asTransactionCommitAmbiguousExceptioninstead (DbContextFactory.cs:558-561,DbContextFactory.cs:655-657).
Opt-in by marker interface, pay only for what you use
The pipeline is registered for every handler, but most decorators are dormant unless the use case
asks for them. The switch is a set of tiny marker / role interfaces in
MMCA.Common.Application.UseCases:
ITransactional(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/ITransactional.cs:6): an empty marker, declared with the interface-body-less syntax, meaning "open a transaction".ICacheInvalidating(.../UseCases/Markers/ICacheInvalidating.cs:8): exposes aCachePrefixstring to evict after success (ICacheInvalidating.cs:22). The prefix must end at a:boundary, and an empty or whitespace value is the opt-out (ICacheInvalidating.cs:15-21). Its entity-keyed formICacheInvalidating<TEntity>(ICacheInvalidating.cs:39) supplies that prefix as a default interface implementation (ICacheInvalidating.cs:42) fromEntityCachePrefix(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/EntityCachePrefix.cs:9), the static builder of the framework's"{type.FullName}:"key space (For<TEntity>()andFor(Type)atEntityCachePrefix.cs:14,:19), so a command names the aggregate it makes stale instead of spelling a string. A command that still declares its own publicCachePrefixcompiles and wins, but the sharedCacheInvalidationConventionTestsBaserule flags it (ICacheInvalidating.cs:34-38).IQueryCacheable(.../UseCases/Markers/IQueryCacheable.cs:8): exposes aCacheKeyplus aCacheDuration(IQueryCacheable.cs:23,:28). Its doc is explicit that the caller is one of the parameters that affect a result and the one that is invisible in the key: the decorator folds it in automatically for a query that also carriesIUserScopedRequest, and a caller-scoped query that does not must put the caller into this key by hand (IQueryCacheable.cs:14-21).ISharedQueryCache(.../UseCases/Markers/ISharedQueryCache.cs:21): the one opt-out in the set, an empty marker declaring that a query addressed at one user nevertheless produces a result every caller may be served, so its entry stays shared (ISharedQueryCache.cs:9-13). Use it only when the result genuinely does not vary by caller (a public profile card, a published-count badge), and state the reason on the query type (ISharedQueryCache.cs:16-19).IFeatureGated(.../UseCases/Markers/IFeatureGated.cs:10): exposes aFeatureNamethat must match a key in theFeatureManagementconfiguration section (IFeatureGated.cs:16).IRequiresPermission(.../UseCases/Markers/IRequiresPermission.cs:34): exposes thePermissionstring the caller must hold (IRequiresPermission.cs:41). An unknown permission is granted by no role and therefore denies every caller, which is a deliberate fail-closed default (IRequiresPermission.cs:38-39). Read the remark before marking a command that does not run inline (IRequiresPermission.cs:24-33): the gate evaluates the current principal, which for a deferred command is the one restored from the scheduling row or the message headers, so work queued with no operator behind it (a buyer's action, an anonymous webhook, a system sweep) must be gated at the edge that accepts it and left ungated here.IHasTimeout(.../UseCases/Markers/IHasTimeout.cs:14): exposes aTimeSpan Timeout(IHasTimeout.cs:21). A value at or belowTimeSpan.Zeromeans "no budget" rather than "fail instantly", so a misconfigured value degrades to the previous behavior instead of breaking every request (IHasTimeout.cs:16-19).
Each decorator does an is-check (command is not ITransactional, query is not IQueryCacheable,
and so on) and passes straight through when the interface is absent. This is
[Rubric §2, Design Patterns] (marker interfaces as declarative opt-in) layered with
[Rubric §1, SOLID] Open/Closed: a new handler turns a concern on by implementing an interface, with
no decorator, registration, or pipeline change. A command that reads nothing pays nothing for
transactions, and an uncached query pays nothing for caching, while the capability is uniformly
present.
Adoption is honest about that, and it is uneven. IQueryCacheable is wired and unit-tested, but
no production query in Common or ADC implements it today. ADC's GetNowNextQuery opts out on
purpose: its endpoints already serve it through a Redis-backed output-cache policy, and a second
per-query cache would only stack a second TTL on the same payload
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/NowNext/GetNowNextQuery.cs:10-12).
The adopter is the Helpdesk reference app (GetTicketByIdQuery,
MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/Tickets/UseCases/GetById/GetTicketByIdQuery.cs:23
with a 5-minute TTL at :29).
MMCA.Store has no IQueryCacheable query at all; its public reads cache at the HTTP OutputCache
layer instead
(ADR-040).
The authorization and timeout markers are adopted, and the pattern of what they are used for is
worth noticing. IHasTimeout goes on the commands whose work is genuinely long or outside the
process: ADC's SetUserAvatarCommand at 60 seconds
(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarCommand.cs:12,
:20), its UploadSessionAssetCommand at 3 minutes
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/UploadFile/UploadSessionAssetCommand.cs:34,
:44), Store's VerifyPaymentCommand at 20 seconds
(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/UseCases/VerifyPayment/VerifyPaymentCommand.cs:20,
:29) and CreateCheckoutSessionCommand at 45 seconds
(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/UseCases/CreateCheckoutSession/CreateCheckoutSessionCommand.cs:16,
:26). IRequiresPermission is carried mostly by internal (deferred) commands, where the
pipeline check is the only one there is because no endpoint policy ran: Store's
SendOrderShippedEmailInternalCommand (.../Orders/InternalCommands/SendOrderShippedEmailInternalCommand.cs:26,
SalesPermissions.OrdersManage at :41) and PublishProductVariantChangedInternalCommand
(.../Products/InternalCommands/PublishProductVariantChangedInternalCommand.cs:29,
CatalogPermissions.ProductVariantsManage at :41), and ADC's ScoreEventSessionsInternalCommand,
which carries both markers (.../Sessions/UseCases/DecisionSupport/ScoreEventSessions/ScoreEventSessionsInternalCommand.cs:27,
ConferencePermissions.SessionSelectionManage at :35, a 12-minute budget at :44). The newest
marker is the one still ahead of its adoption: no use case in MMCA.ADC, MMCA.Store or MMCA.Helpdesk
implements ISharedQueryCache, so it is exercised only by the framework's own tests
(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/CallerScopedQueryCacheTests.cs).
Both caching markers are also inert in a host that has not called AddQueryCaching()
(DependencyInjection.cs:209-213), so implementing IQueryCacheable on a query is only half of the
opt-in.
The generic write side: three verbs a module does not have to write
Below the pipeline sits a second body of shared code: the workflows every aggregate write repeats. They are ordinary handlers, so the decorators wrap them exactly as they wrap a hand-written one.
The create workflow is
CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/CreateEntityHandlerBase.cs:42): prepare
the request, map it through the module's
IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType>
(which runs the entity factory), add, save, log, and map the result through the module's
IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>
(CreateEntityHandlerBase.cs:84-99). Every step is a virtual hook (the add and save together are
PersistAsync, which a create overrides only when it needs a different persist step,
CreateEntityHandlerBase.cs:117-137), so
CreateEntityHandler<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>
(.../UseCases/CreateEntityHandler.cs:28) is the base with nothing overridden: an aggregate whose
create needs no pre-map step, no module-specific log line and no post-commit publish needs no
subclass at all. It is sealed on purpose, because the base, not this, is the extension point
(CreateEntityHandler.cs:14-19). CreateCoreAsync takes the unit of work as a parameter
(CreateEntityHandlerBase.cs:77-81), which is what lets a manual-id create wrap the whole workflow in
a retry loop and run each attempt against a fresh DI scope's unit of work; the ambient DbContext
still tracks the failed insert, so a retry on the injected one would never persist.
The mutate workflow is
MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType>
(.../UseCases/MutateEntityHandlerBase.cs:52): resolve the repository from
IUnitOfWork (MutateEntityHandlerBase.cs:294), load
the aggregate tracked and with the includes the mutation needs (MutateEntityHandlerBase.cs:295),
fail with a NotFound Error stamped with the handler
name and entity type when it is gone (MutateEntityHandlerBase.cs:297; the name is the virtual
HandlerName, which defaults to the concrete handler's own type name, MutateEntityHandlerBase.cs:59-63), stamp the caller's
optimistic-concurrency token back as the original so a stale edit fails the save rather than winning
it (ADR-035,
MutateEntityHandlerBase.cs:299-310), run the domain mutation
(MutateEntityHandlerBase.cs:312-314), and save only when it succeeded
(MutateEntityHandlerBase.cs:330), then log and run the post-save hook
(MutateEntityHandlerBase.cs:332-333). A conditional write gets one extra step before the save: the
root's concurrency token is touched (MutateEntityHandlerBase.cs:327-328), because stamping the
original token does not by itself make the root dirty, so an applier that changed only child rows left
the root Unchanged, EF emitted no root UPDATE, and the caller's If-Match was never evaluated,
letting two writers holding the same ETag both succeed (MutateEntityHandlerBase.cs:321-326). The
core deliberately does not implement
ICommandHandler<in TCommand, TResult>
(MutateEntityHandlerBase.cs:18-27): a single type advertising two handler interfaces would register
a bogus second handler entry during the module scan. Like the create workflow, the core takes the
unit of work as a parameter: MutateCoreAsync has an overload for the attempt's IUnitOfWork (and
one that also takes a caller-supplied MutationContext), so a retrying subclass runs each attempt
against a fresh scope's unit of work, because the ambient DbContext still tracks the failed attempt
(MutateEntityHandlerBase.cs:248-289). Three thin subclasses supply the three shapes a
real handler answers with: a bare Result for verb-style commands
(MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType>,
MutateEntityHandlerBase.cs:347), a Result<TEntityDTO> carrying the refreshed DTO
(MutateEntityHandlerBase.cs:370), and a Result<TResultPayload> the handler builds itself
(MutateEntityPayloadHandlerBase<TCommand, TEntity, TIdentifierType, TResultPayload>,
MutateEntityHandlerBase.cs:415, with an abstract BuildResult the subclass fills in).
MutationContext (.../UseCases/MutationContext.cs:31) is the per-command side
channel that makes those hooks composable without handler instance state, which a scoped handler must
not carry between calls (MutationContext.cs:11-18). It is a typed bag (Set, TryGet,
GetOrDefault, Contains at MutationContext.cs:56, :69, :93, :99) threaded through load,
mutate and the post-save hooks and finally into the result builder, so a value the mutation derived
while the aggregate was loaded (its pre-mutation state, the blob about to be orphaned, a warning the
caller has to see) can reach the response. It also carries the short-circuit: SkipSave()
(MutationContext.cs:49, read back through SaveSkipped at :39) marks the command already satisfied, and the workflow then returns the
loaded aggregate as a success with no save, no LogMutated and no OnMutatedAsync
(MutateEntityHandlerBase.cs:316-319). That is the idempotent no-op (remove an avatar that is not
there, close an already-closed record), which is a success rather than a refused invariant and must
not log a mutation that did not happen.
The update path is where the generic write side pays off most.
UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType>
(.../UseCases/UpdateEntityCommand.cs:48) carries the id, the request and the caller's If-Match
row version, implements ICommandWithRequest<out TRequest> so the
validator bridge finds it, and implements ICacheInvalidating with a defaulted
CachePrefix built by EntityCachePrefix (UpdateEntityCommand.cs:65), because the generic
controller constructs the command itself and cannot supply one. The record is not sealed
(UpdateEntityCommand.cs:28-37): a real update often carries state beside the request (a route-derived
child id, a server-decided flag, a second concurrency token), and a derived positional record inherits
everything, the defaulted prefix included, which it can narrow to a per-verb one
(UpdateEntityCommand.cs:61-64).
UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>
(.../UseCases/UpdateEntityHandler.cs:48) is that command's handler: it maps EntityId and
RowVersion off the command and implements MutateAsync as one call into the module's
IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>
(UpdateEntityHandler.cs:84-92), which is the piece that knows field names. The derived-command twin
UpdateEntityCommandHandler<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>
(UpdateEntityHandler.cs:185) runs the same workflow but hands the whole command to an
IEntityUpdateCommandApplier<TEntity, TUpdateRequest, TIdentifierType, in TCommand>
(.../UseCases/IEntityUpdateCommandApplier.cs:38, applied at UpdateEntityHandler.cs:218-223), so
state the server decided stays on the command instead of being smuggled into a request DTO a caller
could set (IEntityUpdateCommandApplier.cs:14-21). Both appliers answer with a bare
Result, because the instance handed in is the tracked
one: a successful apply has already mutated it, and a refusal must leave it untouched
(IEntityUpdateCommandApplier.cs:28-32,
MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityDTOMapper.cs:79). Neither handler
raises events: domain events belong to the aggregate's own mutation methods, which is what keeps the
generic path and a hand-written one indistinguishable from the outside (UpdateEntityHandler.cs:33-37).
Delete is the shortest complete example.
DeleteEntityCommand<TEntity, TIdentifierType>
(.../UseCases/DeleteEntityCommand.cs:13) is a one-property record with the same defaulted cache
prefix and the same empty-string opt-out (DeleteEntityCommand.cs:16-22), and its TEntity parameter
earns its keep twice: it distinguishes DeleteEntityCommand<Session, int> from
DeleteEntityCommand<Speaker, int> so DI routes each to its own handler, and it supplies that
prefix (DeleteEntityCommand.cs:5-9).
DeleteEntityHandler<TEntity, TIdentifierType>
(.../UseCases/DeleteEntityHandler.cs:36) loads the aggregate (DeleteEntityHandler.cs:71-72),
returns NotFound when the row is missing (DeleteEntityHandler.cs:74), gives a pre-delete
invariant its chance to refuse through OnDeletingAsync (DeleteEntityHandler.cs:76-78), calls the
aggregate's own Delete() (which enforces invariants and may raise domain events), and saves only
when that succeeded (DeleteEntityHandler.cs:80-86). It is left unsealed and split into overridable
steps because the two things a real delete outgrows are structural rather than behavioral: the child
collections the aggregate's cascade has to see (Includes, DeleteEntityHandler.cs:58) and a
cross-aggregate refusal (DeleteEntityHandler.cs:12-21).
Two more bases cover child collections.
AddChildEntityHandlerBase<TCommand, TParent, TIdentifierType, TChild, TChildDTO>
(.../UseCases/ChildEntityHandlerBase.cs:43) loads the parent tracked with its child collection
included, calls the aggregate method that owns the invariant, saves on success, and maps the new child
through an abstract MapChild rather than an injected DTO mapper, because the DTO belongs to the
child, whose identifier type is usually not the parent's (ChildEntityHandlerBase.cs:21, abstract MapChild at :87,
workflow at ChildEntityHandlerBase.cs:121-162). Includes is abstract on purpose: loading the child
collection is what makes the aggregate's duplicate check meaningful, so naming it has to be a
deliberate act, and an unloaded collection turns a double submit into a raw unique-index 409
(abstract at ChildEntityHandlerBase.cs:68).
RemoveChildEntityHandlerBase<TCommand, TParent, TIdentifierType>
(ChildEntityHandlerBase.cs:180) is the mutate workflow with Includes promoted from virtual to
abstract for the same reason: a remove that cannot see the collection cannot find the child and
reports the wrong NotFound (ChildEntityHandlerBase.cs:170, :189).
Registration for all of this is three extension methods, each of which registers closed, not
open-generic, service types (decoration wraps concrete service types, and an open
registration would resolve completely undecorated) and each of which uses TryAdd, so a module that
outgrows one verb registers its own handler ahead of the call and keeps the generic pair for the other
two. AddEntityCrud<...>() (DependencyInjection.Crud.cs:74) registers create, update and delete plus
the update command's validator bridge (DependencyInjection.Crud.cs:82-96);
AddEntityUpdateVerb<...>() (DependencyInjection.Crud.cs:136) registers one verb of the applier-
discriminated update (DependencyInjection.Crud.cs:144-152); and AddEntityUpdate<...>()
(DependencyInjection.Crud.cs:187) registers the derived-command handler
(DependencyInjection.Crud.cs:195-199). All three are adopted: MMCA.Helpdesk's Tickets module calls
AddEntityCrud after its scan
(MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/DependencyInjection.cs:54,
with the ordering rationale at :41), and MMCA.Store's Catalog, Sales and Identity modules use the
same idiom. This whole family is [Rubric §15, Best Practices & Code Quality] and [Rubric §5, Vertical Slice]
pulling in the same direction: a straightforward CRUD slice becomes a request DTO, a mapper, an
applier and one registration line, while the moment a slice needs something of its own it drops back
to the base class and keeps the shared workflow.
Declaring the contract: the opt-in request markers
ICommand<TResult> (.../UseCases/ICommand.cs:31) and
IQuery<TResult> (.../UseCases/IQuery.cs:26) let a request DTO declare the result
type its handler produces. Both are body-less interfaces whose single type parameter is a phantom:
nothing consumes it in a member, and the Sonar suppression on each says exactly why
(ICommand.cs:27-30, IQuery.cs:22-25). They are purely additive. Handlers keep implementing
ICommandHandler<in TCommand, TResult>, nothing in the
registration or the decorator pipeline reads them, and a request that does not carry one behaves
identically (ICommand.cs:14-19).
The pay-off is CqrsContractInspector
(.../UseCases/CqrsContractInspector.cs:72), a reflection-only static that walks the concrete types in
a set of assemblies (CqrsContractInspector.cs:83-99), reads each handler interface it implements
(CqrsContractInspector.cs:103-119), and compares the handler's TResult against the marker the
request carries (CqrsContractInspector.cs:122-148). It reports two things, classified by
CqrsContractMismatchKind (CqrsContractInspector.cs:8): a
ResultType disagreement, and a HandlerKind one where a request declared as a command is handled by
an IQueryHandler or vice versa. Each finding is a
CqrsContractMismatch record (CqrsContractInspector.cs:31) that renders
itself as a fitness-test failure line through Describe() (CqrsContractInspector.cs:42-50). Two
design choices keep it usable: a request carrying no marker is ignored entirely, so adoption stays
gradual and a repo with zero adoption sees an empty list rather than a wall of failures
(CqrsContractInspector.cs:59-65), and open generic handler definitions (the framework's own
decorators and every generic handler base above) are skipped, because their request type argument is a
type parameter rather than a request (CqrsContractInspector.cs:66-70, filter at
CqrsContractInspector.cs:91). The inspector degrades gracefully when a missing transitive reference
makes Assembly.GetTypes() throw, keeping the types that did load
(CqrsContractInspector.cs:169-179).
That is [Rubric §9, API & Contract Design] and [Rubric §14, Testability] offered rather than
imposed, and the honest status is that nothing has taken the offer yet: no MMCA.ADC, MMCA.Store or
MMCA.Helpdesk request implements either marker, and FindContractMismatches is called only from the
framework's own
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/UseCases/CqrsContractInspectorTests.cs.
Tenant scoping and the stampede lock
Both caching decorators are multi-tenant aware, and the reason is a nice illustration of where a
cross-cutting concern has to live. ICacheService is a singleton and therefore cannot see the
scoped tenant, so two tenants computing the same cache key would serve each other's rows. Isolation
is applied where the key is computed instead: TenantCacheKey
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TenantCacheKey.cs:25) turns a
key or prefix into t:{tenantId}:{key} when ITenantContext
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ITenantContext.cs:25) reports a resolved
tenant, and returns it untouched when it does not (TenantCacheKey.cs:37-40, marker constant at
TenantCacheKey.cs:28). The scoped form is a prefix, not a suffix, precisely so prefix eviction
keeps working: a command's invalidation can only reach its own tenant's entries
(TenantCacheKey.cs:15-19). Because the query decorator uses the same helper for its reads
(CachingQueryDecorator.cs:58-59) and the command decorator for its evictions
(CachingCommandDecorator.cs:106), reads and invalidations stay symmetric by construction.
ITenantContext is injected as an optional constructor parameter defaulting to null
(CachingQueryDecorator.cs:47, CachingCommandDecorator.cs:47), so a single-tenant host keeps
byte-identical cache keys to the pre-tenancy framework
(ADR-073). The interface itself
is one scoped instance per request, populated once at the edge and read by the persistence layer as
well as by these decorators (ITenantContext.cs:3-8, :11-12). It exposes TenantId, IsResolved
and IsAllTenants (ITenantContext.cs:31, :34, :40). An unresolved tenant has no generated
fallback and fails closed, reading no tenant-owned rows at all; a system operation that must see
every tenant (a processor, a seeder, a retention sweep) says so explicitly through SetAllTenants()
(ITenantContext.cs:59), so "see everything" is always a decision in code and never the accident of
a request that carried no tenant (ITenantContext.cs:12-16). The declaration widens reads, not
inserts: an all-tenants scope still names an explicit tenant on each new row, and a scope that
resolved no tenant without the declaration may not write a tenanted row at all
(ITenantContext.cs:52-57). One scope gets one answer: SetTenant
(ITenantContext.cs:50) and SetAllTenants each accept the state already held and throw on any
other, because a scope whose tenant changed mid-flight would already have read rows under the
previous answer (ITenantContext.cs:18-23, :47-49, :58).
The caller is scoped the same way, and for a sharper reason.
UserCacheKey
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/UserCacheKey.cs:26) appends
:u:{userId} to the key of a query that implements IUserScopedRequest, unless the query opts out
with ISharedQueryCache (UserCacheKey.cs:29, :38-41). A per-user query
("my orders", "my profile") whose author followed IQueryCacheable's guidance to include every
parameter that affects the result still leaves out the one parameter that is not on the request, who
is asking, so two callers compute the same key against one shared cache and the second is served the
first's personal data for the whole cache duration (UserCacheKey.cs:11-16). The caller marker is a
suffix where the tenant marker is a prefix, and that asymmetry is deliberate: ICacheInvalidating
commands evict by prefix, so a caller segment inserted ahead of the key would put every user's entry
outside the prefix the invalidating command computes and nothing would ever be evicted, while
appending it leaves the prefix intact and one command still clears every caller's copy. Over-eviction
across users is harmless; the leak it closes is not (UserCacheKey.cs:18-23). The decorator composes
the two scopes in one place, caller first and tenant outermost
(CachingQueryDecorator.cs:58-59, :50-54), so read, stampede lock and populate all agree on the
same key (CachingQueryDecorator.cs:69-71).
The read path also guards against cache stampede. On a miss,
CachingQueryDecorator<TQuery, TResult> takes a per-key lock
and re-checks the cache inside it, so on expiry of a hot key exactly one caller runs the handler and
the rest are served the fresh entry (CachingQueryDecorator.cs:98-105). The wait on that lock is
bounded by Cache:PopulateLockTimeout, bound into
QueryCachePipelineSettings
(MMCA.Common/Source/Core/MMCA.Common.Application/Settings/QueryCachePipelineSettings.cs:20), whose
default is five seconds (DefaultPopulateLockTimeout, QueryCachePipelineSettings.cs:30, applied
as the property initializer at :43); zero or a negative value removes the bound, so waiters block
until the populate finishes (QueryCachePipelineSettings.cs:40-41). A waiter that exhausts a finite budget is fail-open like every other cache failure here, so
it runs the handler itself and returns the answer deliberately uncached, leaving the entry to the
request that holds the lock (CachingQueryDecorator.cs:87-96). The miss counter is incremented once,
at the point where execution actually falls through to the handler rather than at either cache read,
so a request that misses the fast path and the double-check is not counted twice
(CachingQueryDecorator.cs:107-113). The lock table is
QueryCacheKeyLocks (.../Decorators/CachingQueryDecorator.cs:263), a
non-generic holder around a KeyedSemaphoreStripe so that
every closed generic decorator shares one table rather than one per closed type
(CachingQueryDecorator.cs:242-267). It is striped rather than one semaphore per key, and it is
honest about the limit: the lock is per process, so
across replicas stampede protection is at most one handler execution per instance, not one
cluster-wide (CachingQueryDecorator.cs:256-260).
One key shape steps out of the host's namespace altogether. A shared store qualifies every key with
the host's own namespace (Cache:KeyPrefix, or the per-service Application:Namespace), so two
services of one deployment never read each other's entries. That is right for nearly every key and
wrong for a record one service writes and another reads, such as the soft-deleted-user marker
Identity writes and every service's middleware reads
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/CrossServiceCacheKeys.cs:3-17).
CrossServiceCacheKeys (CrossServiceCacheKeys.cs:24) reserves the
segment for that case: a key that starts with Prefix, "xsvc:" (CrossServiceCacheKeys.cs:27,
tested by the ordinal IsCrossService at :32-36), is qualified with the deployment-wide
cross-service namespace instead (Cache:CrossServiceKeyPrefix, falling back to the token audience
Jwt:Audience, since the services that accept one audience's tokens are exactly the ones that must
honor a revocation of them). Such a key carries no generation token, so a prefix wipe in one service
cannot hide the record from the others, and it is removed by its exact key
(CrossServiceCacheKeys.cs:20-21).
The supporting pieces
Every short-circuiting decorator in the chain is a thin shell over a shared internal static, and
that is a design rule rather than a coincidence. A command decorator and its query twin differ only
in which generic parameter names the request, so each decision lives once:
FeatureFlagGate (.../Decorators/FeatureFlagGate.cs:12),
AuthorizationGate (.../Decorators/AuthorizationGate.cs:18),
ValidationGate (.../Decorators/ValidationGate.cs:12) and
TimeoutBudget (.../Decorators/TimeoutBudget.cs:11), each documented as shared
"so the two cannot drift" (FeatureFlagGate.cs:7-11, AuthorizationGate.cs:13-17,
ValidationGate.cs:8-11, TimeoutBudget.cs:7-10). The three gates answer with an Error (or an
error list) or null and never build the caller's TResult; the budget, which owns the call to the
inner handler, returns either that handler's result or the timeout failure.
ValidationGate carries one private helper of its own, RequestShape<T>
(ValidationGate.cs:57): a static class per closed request type whose WrapsRequest field records,
computed once per type, whether the command embeds a request DTO through
ICommandWithRequest<out TRequest> (ValidationGate.cs:59-61).
The gate passes that flag with the request type name to the wire-error builder
(ValidationGate.cs:40-43), because every validator over such a command, the framework bridge and an
explicit command validator that nests the request validator alike, reports the request's properties
under a Request. path; dropping that segment from the synthesized code lets a rule answer under one
code whichever validator ran it (ValidationGate.cs:49-55).
Building the TResult failure is two more helpers.
ResultFailureFactory
(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ResultFailureFactory.cs:11)
builds a delegate that manufactures a TResult failure from an error list (Build<TResult>() at
ResultFailureFactory.cs:20), taking a direct cast for non-generic Result
(ResultFailureFactory.cs:22-25), compiling an expression tree once per closed Result<T>
(ResultFailureFactory.cs:27-41), and throwing InvalidOperationException for anything else
(ResultFailureFactory.cs:43-45). ResultFailure<TResult>
(.../Decorators/ResultFailure.cs:19) is the one place that delegate is cached: a static field per
closed TResult, filled by From with ??= on first use (ResultFailure.cs:21, :26-27). It is
built lazily, on the first short-circuit, never in a static constructor, because the pipeline
decorates every handler unconditionally and an eager initializer would turn an unsupported TResult
into a TypeInitializationException at resolve time for a handler that never short-circuits; a
benign duplicate build under a race produces an equivalent delegate (ResultFailure.cs:10-17). Every
short-circuit goes through it: the view-as guard (ViewAsCommandDecorator.cs:31), both feature gates
(FeatureGateCommandDecorator.cs:31, FeatureGateQueryDecorator.cs:30), both authorization
decorators (AuthorizationCommandDecorator.cs:40, AuthorizationQueryDecorator.cs:35), both
validators (ValidatingCommandDecorator.cs:53, ValidatingQueryDecorator.cs:56) and the timeout
budget (TimeoutBudget.cs:50). That remark is a good example of the guide's general rule: read the
remarks, they usually record a bug that was paid for once.
CqrsMetrics (.../Decorators/CqrsMetrics.cs:21) is the internal static holder of
the MMCA.Common.Cqrs OpenTelemetry meter (CqrsMetrics.cs:24-26) and its six instruments: command
and query duration histograms in milliseconds (CqrsMetrics.cs:29-38), the query cache hit/miss
counters the caching decorator increments (CqrsMetrics.cs:41-50, recorded at
CachingQueryDecorator.cs:77, :94, :103, :113), and the two short-circuit counters,
cqrs.authorization.denied.count and cqrs.timeout.count, both tagged request_type
(CqrsMetrics.cs:53-62, recorded through RecordAuthorizationDenied and RecordTimeout at
CqrsMetrics.cs:76-82). A permission that is denying far more traffic than expected, or a handler
that keeps exhausting its budget, is therefore visible as a metric rather than only as a client-side
error rate (CqrsMetrics.cs:15-19). The meter name is duplicated as a literal in MMCA.Common.Aspire
because that package has no reference to Application (CqrsMetrics.cs:8-10), which is the one place
this group's metrics leak into another layer.
The other Application-layer contracts in this group
Several contracts sit beside the pipeline rather than inside it. They are declared here, in the Application layer, and implemented in Infrastructure or the composition root, which is what keeps a use case that depends on one extractable into its own service.
IDistributedLock
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IDistributedLock.cs:30) is best-effort
mutual exclusion on a logical key across every replica of a service. Its single method
TryAcquireAsync(key, ttl, wait, cancellationToken) returns an IAsyncDisposable handle or null
when the key was still held after wait elapsed (IDistributedLock.cs:59-63). The XML doc is
explicit about the three things that make it safe to use: it is not reentrant
(IDistributedLock.cs:19-22), the TTL is a crash guard rather than a lease you may rely on, so a
paused holder can lose the lock without knowing (IDistributedLock.cs:37-42), and release is
owner-scoped and idempotent (IDistributedLock.cs:54-57). No decorator takes it; its in-framework
caller is the API idempotency filter, which needs its execute-then-store window to be exclusive across
replicas (IdempotencyFilter,
MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:153, acquisition at
IdempotencyFilter.cs:269,
ADR-017), and the implementation
(RedisDistributedLock or the
InProcessDistributedLock fallback)
is chosen at the composition root (G14).
IScheduledJob (.../Interfaces/IScheduledJob.cs:36) is recurring work driven by a
five-field cron expression, with three members: a stable Name that doubles as the primary key of the
persisted job row (IScheduledJob.cs:44), a default CronExpression a host may override per job
through Scheduler:Jobs:{Name}:Cron (IScheduledJob.cs:68, :65), and ExecuteAsync
(IScheduledJob.cs:78). Occurrences are computed against the UTC clock, never a local or
configured time zone, so a schedule never shifts, doubles, or vanishes across a daylight saving
transition (IScheduledJob.cs:58-62). Four behaviors documented on the interface shape how you write
one: jobs resolve scoped, in a fresh DI scope per execution, so they may take a unit of work and
must hold no state between runs (IScheduledJob.cs:10-14); a claim lease in the job store makes an
occurrence run exactly once across replicas (IScheduledJob.cs:17-19); missed occurrences do not
pile up, so work that must not be skipped has to be idempotent and range-driven rather than
one-run-per-tick (IScheduledJob.cs:26); and a thrown exception is caught, logged, and stamped as a
failed outcome without retry inside the occurrence (IScheduledJob.cs:31). The runner lives in
ScheduledJobRunner
(ADR-074).
IAuditTrailReader (.../Interfaces/IAuditTrailReader.cs:20) reads the
recorded change history of one entity, keyed by the entity's full CLR type name and the invariant
string form of its primary key (composite keys joined in model key order), paged and newest first
(GetForEntityAsync, returning an IReadOnlyList<AuditHistoryEntryDTO>, at IAuditTrailReader.cs:40,
summary at :23, ordering note at :17). It is registered
only by AddAuditTrail, so a host that never opted in has nothing to resolve
(IAuditTrailReader.cs:6), and the framework deliberately ships the read without an endpoint or page,
because who may see an entity's history is an application decision (IAuditTrailReader.cs:11). The
implementation is AuditTrailReader over the rows
written by
AuditTrailSaveChangesInterceptor
(ADR-075); this is
[Rubric §30, Compliance, Privacy & Data Governance] territory.
IAuditTrailWriter (.../Interfaces/IAuditTrailWriter.cs:24) is the explicit
counterpart for events a save never sees, such as a personal-data export: its one member, RecordAsync
(IAuditTrailWriter.cs:41-46), writes a row with the same identifying columns only (entity type, key,
operation, who and when) and no before or after value (IAuditTrailWriter.cs:10-14), so the event
shows up in the history IAuditTrailReader returns. Unlike the reader it is always registered by
AddInfrastructure, and it records nothing while the trail is off (IAuditTrailWriter.cs:17-19). The
implementation is AuditTrailWriter, and
ExportUserDataHandlerBase is its caller
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:64).
IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>
(.../Interfaces/IEntityDTOProjector.cs:51) is the opt-in pushdown counterpart of
IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>:
a mapper maps rows after they materialize, so the query must select whole entities, while a
projector rewrites the queryable so the provider selects the DTO's columns directly
(IEntityDTOProjector.cs:11-15). Its one method is
IQueryable<TEntityDTO> ProjectTo(IQueryable<TEntity> source) (IEntityDTOProjector.cs:56), and the
implementation must stay translatable: no materializing inside it (IEntityDTOProjector.cs:51-52), and
no instance sub-mappers, custom mapping methods, or after-map hooks, because a projection is an
expression tree the database provider has to translate (IEntityDTOProjector.cs:31-34). Registering
one is the whole opt-in: the module scan picks it up scoped beside the mappers
(DependencyInjection.ModuleScanning.cs:63), and
EntityQueryService<TEntity, TEntityDTO, TIdentifierType>
declares a second, longer constructor purely so the container selects the projected path when one is
registered and the plain path when it is not. Because the two paths are chosen by registration, a
projector that disagrees with its mapper would make a response depend on which one happened to be
wired, which is why the contract says to pin the equivalence with a test
(IEntityDTOProjector.cs:43-45). That is [Rubric §12, Performance & Scalability] again, this time on
the read path (ADR-034).
IEventUpcaster (.../Interfaces/IEventUpcaster.cs:28) and
IEventUpcasterRegistry (.../Interfaces/IEventUpcasterRegistry.cs:24)
are the versioning contracts for integration events, declared in this layer because both delivery
paths consume them. A breaking event-shape change is a new event type plus a consumer-side
upcaster, never a silent reshape of the existing type
(ADR-010), and the
typed IEventUpcaster<in TSource, out TTarget> (IEventUpcaster.cs:67) is the one an application
writes: it supplies SourceType, TargetType, and the non-generic Upcast as default interface
implementations (IEventUpcaster.cs:72-75), so the class body is the single typed conversion method
(IEventUpcaster.cs:82). Registration is one call,
services.AddEventUpcaster<TSource, TTarget, TUpcaster>() (DependencyInjection.Extensibility.cs:81), which
appends a singleton to an enumerable so several upcasters compose into a chain. The registry
(IEventUpcasterRegistry.cs:24) is the composed view: it probes whether a type has an upcaster
(IEventUpcasterRegistry.cs:31), resolves the terminal (newest) contract by walking the whole chain
(IEventUpcasterRegistry.cs:39), and upcasts an instance hop by hop
(IEventUpcasterRegistry.cs:48). Two properties make it safe to depend on unconditionally: it is
always registered, and with no upcasters its operations are identity
(DependencyInjection.cs:43-47, IEventUpcasterRegistry.cs:15); and every hop preserves the
envelope, restamping MessageId and DateOccurred from the pre-hop instance, so consumer-side inbox
deduplication keeps working on the id the producer published (IEventUpcaster.cs:23). A bad
registration graph (duplicate source, a source mapped onto itself, or a cycle) throws from the
implementation's constructor and is resolved at host start, so a misconfiguration fails the host
rather than the first message (IEventUpcasterRegistry.cs:18-20). The in-process consumer is the
DomainEventDispatcher, the broker-side one is
UpcastingIntegrationEventConsumer<TEvent>
(ADR-090).
ICounterStore (.../Interfaces/ICounterStore.cs:23) is the atomic fixed-window
counter behind the framework's rate limits and brute-force throttles: login failure counts,
registration and token-request throttles
(ADR-029,
ICounterStore.cs:3-7). It stays apart from ICacheService
because a counter needs an atomic increment and an expiry anchored to its first increment, which a
get followed by a set cannot give. Its three members are IncrementAsync(key, window), which returns
the new value and rejects a zero or negative window (ICounterStore.cs:34, :33), GetAsync for a
check that runs before the counted action (ICounterStore.cs:43), and ResetAsync, so a successful
sign-in clears its failure count (ICounterStore.cs:52). The window is fixed: the increment that
creates a counter sets its lifetime and later increments never extend it, so a caller who keeps
hitting a counter cannot hold it open (ICounterStore.cs:11-13). The store is shared across replicas
when Redis is registered (RedisCounterStore) and
process-local otherwise, the same choice IDistributedLock makes, and a Redis fault never fails the
caller: the store logs a warning at most once a minute and counts in-process until Redis answers
again, so a limit keeps applying per replica rather than failing every request or switching off
(ICounterStore.cs:16-20).
IInboxRecorder (.../Interfaces/Events/IInboxRecorder.cs:20) is the
consumer-side half of the inbox
(ADR-021). Stage
(IInboxRecorder.cs:26) adds the inbox row to the current scope's unit of work, unsaved, so a
handler's own SaveChangesAsync commits it in the same transaction as its writes: a rollback
discards both, and no crash can land between them (IInboxRecorder.cs:4-9). A handler that never
saves leaves the row to be discarded with its scope, and the broker consumer records the row after
the handler returns, so the duplicate is absorbed either way (IInboxRecorder.cs:9-11).
RevokeAsync (IInboxRecorder.cs:40) is the undo: when a handler fails after a save already
committed its row, it deletes that row from a fresh scope so the redelivery runs the handler again,
and it is set-based and idempotent (IInboxRecorder.cs:28-34). Its caller is
ScopedIntegrationEventHandlerBase, which stages from the scope it opens per delivery before the
subclass runs (IInboxRecorder.cs:7-8). It is registered by Infrastructure only when the inbox is
enabled, and staging is inert outside a broker consume of that same handler and message, so the
in-process dispatch of an integration event never writes inbox rows (IInboxRecorder.cs:14-17).
INavigationPopulatorCoverage
(.../Interfaces/Navigation/INavigationPopulatorCoverage.cs:13) lets a navigation populator declare
which navigations it loads, through one method, bool Handles(NavigationPropertyInfo navigation)
(INavigationPopulatorCoverage.cs:18), so the host-start check can prove that every navigation EF
Core cannot include (a cross-data-source one) has a loader (INavigationPopulatorCoverage.cs:3-6).
That check is
NavigationPopulatorStartupValidator,
which fails host start when a cross-source navigation is left on the no-op default populator that
AddApplication() registers (DependencyInjection.cs:52-58).
DeclarativeNavigationPopulator<TEntity>
answers from its descriptors and the null populator handles nothing, while a hand-written populator
that does not implement the interface is trusted to handle every navigation of its entity, because
nothing about its code can be inspected (INavigationPopulatorCoverage.cs:7-12,
ADR-002).
ICreateRequest (.../Interfaces/ICreateRequest.cs:8) is the smallest type in the
group: an empty marker used purely as a generic constraint by
IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType>
so request-to-entity mapping is type-safe (ICreateRequest.cs:3-7), and by
CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>
(CreateEntityHandlerBase.cs:47). It pairs with
ICommandWithRequest<out TRequest>
(.../UseCases/ICommandWithRequest.cs:14), whose single covariant Request property
(ICommandWithRequest.cs:17) is what the module scan looks for when it auto-registers the delegating
validator described above (ICommandWithRequest.cs:5-11).
Where this fits, and the failure-mode contract
These contracts sit in the Application layer of Clean Architecture
(primer §1), above Domain and below Infrastructure and the API. The
API layer (G12) resolves a closed handler from DI and calls
HandleAsync; the decorators it gets are invisible to the caller, and returned Result failures are
translated to HTTP status codes by
ApiControllerBase. Domain events raised inside
the transaction reach the outbox on save (G04,
ADR-003). Note that HTTP request
idempotency is not a decorator in this group: it is an API-layer filter that borrows this group's
IDistributedLock contract. And because the only things handlers and decorators
depend on are abstractions,
IUnitOfWork,
ICacheService,
ICorrelationContext,
ITenantContext,
ICurrentUserService,
IPermissionRegistry, IFeatureManager, IValidator<T>, the
whole pipeline survives a module being extracted into its own service unchanged
([Rubric §7, Microservices Readiness],
ADR-007 and
ADR-008).
The contract to memorize, because the rest of the system relies on it, has four clauses. On a
business failure (a Result with IsFailure, no exception thrown) the transaction is rolled
back, atomicity over partial persistence, and cache invalidation is skipped
(DependencyInjection.cs:138-139, enforced at DbContextFactory.cs:643-649 and
CachingCommandDecorator.cs:80-85). On an exception the transaction also rolls back and the
exception propagates outward through every decorator, which records the outcome and tags the metric
exception, leaving the stack to the boundary that finally handles it
(DependencyInjection.cs:140, LoggingCommandDecorator.cs:71-90). On a short circuit (a view-as
caller on a command, feature off, permission denied, validation failed, budget expired) the handler
is never called at all and the caller gets a typed failure whose ErrorType is the decorator's own:
Forbidden, NotFound, Forbidden, Validation, Unavailable respectively. And on the read side only
non-failure results are ever cached (CachingQueryDecorator.cs:118). Note the revision history here: rollback-on-business-failure is the
current semantic, adopted in the 2026-07-19 revision of
ADR-014; older prose that said
a business failure still commits describes a framework version that no longer exists. The asymmetry
that remains, failures are values that flow through the pipeline while exceptions are escapes that
unwind it, is the same Result-pattern discipline the whole codebase is built on, expressed here as the
rules of the pipeline.
ICreateRequest
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Mapping·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/ICreateRequest.cs:8· Level 0 · interface (marker, empty)
- What it is: an empty marker interface for "create" request DTOs, used as a generic type constraint by IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType> and by the framework's generic create handler and controller bases, so the create path is distinguishable from every other mapping path at the type-system level.
- Depends on: nothing. Same presence-as-signal marker pattern as ITransactional.
- Concept introduced, type-system constraints as documentation and enforcement.
[Rubric §9, API & Contract Design]assesses how request contracts are modelled and kept unambiguous; tagging a DTO as "this is a create" lets the generic mapper, handler and controller infrastructure refuse anything that is not a create request on the create path, catching a wiring mistake at compile time rather than at runtime. - Walkthrough: the body is empty (
ICreateRequest.cs:8-10); the XML doc (ICreateRequest.cs:3-7) names the constraint site. All of the type's value is in the hierarchy: there is no member to implement, so opting in costs a base-list entry and nothing else. - Why it's built this way: a mapper constrained to
where TCreateRequest : ICreateRequestmakes it impossible to pass a non-create DTO into the create-mapping path, with no runtime check needed and no reflection. - Where it's used: as a generic constraint in six framework declarations, all of them writing
where TCreateRequest : ICreateRequest. In Application: IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityDTOMapper.cs:42-45, the file that hosts both write-side mapper contracts),CreateEntityHandlerBase(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/CreateEntityHandlerBase.cs:47) andCreateEntityHandler(.../UseCases/CreateEntityHandler.cs:33). In the API layer:IAggregateRootEntityControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/IAggregateRootEntityControllerBase.cs:22),AggregateRootEntityControllerBase(.../Controllers/AggregateRootEntityControllerBase.cs:43) andCrudEntityControllerBase(.../Controllers/CrudEntityControllerBase.cs:71). Implemented by create-request DTOs in every module: 7 inMMCA.ADC/Source(EventCreateRequest,SessionCreateRequest,SpeakerCreateRequest,SponsorCreateRequest,QuestionCreateRequest,ActivityCreateRequest,ConferenceCategoryCreateRequest), 8 inMMCA.Store/Source(ProductCreateRequest,ProductVariantCreateRequest,CategoryCreateRequest,OrderCreateRequest,CustomerCreateRequest,ShoppingCartCreateRequest,ShoppingCartItemCreateRequest,InventoryItemCreateRequest) and one in the reference app (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/Tickets/UseCases/Create/TicketCreateRequest.cs). - Caveats / not-in-source: the marker says "create", not "valid". Nothing in the type system checks that an
ICreateRequestomits an identifier or carries the fields the aggregate factory needs; that is FluentValidation's and the factory's job.
IDistributedLock
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IDistributedLock.cs:30· Level 0 · interface
- What it is: a one-method contract for mutual exclusion on a logical string key across every replica of a service.
TryAcquireAsynchands back anIAsyncDisposablehandle whose disposal releases the lock, ornullwhen the key was still held elsewhere after the caller's wait elapsed. - Depends on: BCL only (
Task,TimeSpan,IAsyncDisposable,CancellationToken), no first-party types. Its two implementations live in Infrastructure: InProcessDistributedLock and RedisDistributedLock. Contrast the per-process KeyedSemaphoreStripe, which is exactly what this interface exists to outgrow. - Concept introduced, cross-replica mutual exclusion as an Application-layer abstraction.
[Rubric §12, Performance & Scalability]assesses whether a design still holds once the service scales out horizontally, and the XML doc opens with precisely that failure (IDistributedLock.cs:6-13): aSemaphoreSlim(or a striped one) serializes callers inside one process, so a service running more than one replica executes an "only one of these at a time" section once per replica.[Rubric §29, Resilience, Reliability & Business Continuity]assesses behavior under partial failure; this contract is documented as best-effort, not a consensus protocol (IDistributedLock.cs:23-28): a holder paused past its time-to-live loses the lock without being told, so the guarded section must stay correct (merely slower, or duplicated) when exclusion is lost. The doc states the usage rule bluntly: take the lock to collapse duplicate work, never as the only guard on a correctness invariant that persistence can enforce.[Rubric §3, Clean Architecture]assesses whether the core depends on abstractions while technology choices sit at the edge; the contract carries no transport type at all, so the StackExchange.Redis dependency stays in Infrastructure and callers here never see it. - Walkthrough: line 30 declares the interface; lines 59-63 declare its single member,
Task<IAsyncDisposable?> TryAcquireAsync(string key, TimeSpan ttl, TimeSpan wait, CancellationToken cancellationToken = default). Every parameter carries a contract the implementations must honour.keyis the logical name that callers sharing one backing store have to agree on (IDistributedLock.cs:36).ttlis the crash guard: how long the lock survives with no explicit release, so a holder that dies mid-section cannot wedge the key; it must sit comfortably above the guarded section's expected duration, because work that outlives the TTL is no longer protected (:37-42).waitis how long to block for a current holder, andTimeSpan.Zeromakes the call a single non-blocking attempt (:43-46). The token cancels the wait, not the work that follows it (:47). The return contract matters as much as the parameters:nullmeans "still held elsewhere afterwaitelapsed", and the handle is meant to be disposed inside anawait usingso release happens even when the guarded work throws (:48-53). Release is owner-scoped and idempotent (:54-58): disposing a handle whose TTL already lapsed is a no-op, not a release of whatever holder now owns the key. Two remarks bound usage further: implementations are singletons and must be safe to call concurrently (:17), and the lock is not reentrant, so a caller that already holdskeyand asks for it again waits for itself and then fails to acquire (:20-21). - Why it's built this way: ADR-017 records the change that introduced it. The idempotency filter's execute-then-store window was previously guarded only by a process-local striped semaphore, which stops serializing anything the moment a service runs more than one replica, and both deployed apps do. Putting the contract in
MMCA.Common.Application.Interfacesrather than Infrastructure is what lets the API filter depend on "a lock" while the Redis-versus-process-local decision stays a composition-root concern. - Where it's used: the Infrastructure composition root registers exactly one implementation inside
AddCaching(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:115-129), choosing RedisDistributedLock when anIConnectionMultiplexeris resolvable (:87-93) and the warn-once InProcessDistributedLock otherwise (:95-97); the comment above the registration explains the pairing with the cache (:80-83). Two production consumers exist today.- The framework's IdempotencyFilter resolves it from request services (
MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:153) and spans the double-check plus action plus cache-store window with a 30-secondttl(LockTimeToLive,:97) and a 5-secondwait(LockWait,:104), callingTryAcquireAsyncat:249-251. When that wait expires with nothing cached it answers a 409 in-flight-duplicate result instead of executing a second time (:261-273); when the lock call itself throws, it records a degraded metric and executes anyway rather than failing the request (:253-259). - MMCA.ADC's
ScoreEventSessionsInternalCommandHandlertakes the lock per event around an AI-scoring pass (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/DecisionSupport/ScoreEventSessions/ScoreEventSessionsInternalCommandHandler.cs:84-86) with a 15-minuteClaimTimeToLive(:53) and aClaimWaitofTimeSpan.Zero(:60), so a second replica that cannot claim the event simply skips its pass (:79-83). The inline rationale (:14-21) is a good worked example of both halves of the contract: the handle's disposal releases on every exit path, and the TTL releases for a replica that never reaches an exit path at all.
- The framework's IdempotencyFilter resolves it from request services (
- Caveats / not-in-source:
MMCA.Store/Sourcehas noIDistributedLockconsumer today. The idempotency filter also resolves it withGetService<IDistributedLock>()and falls back to the striped-semaphore path when the result isnull(IdempotencyFilter.cs:153-158), even thoughAddCachingregisters an implementation unconditionally, so that fallback is reachable only in a host that never callsAddCaching(or a test building its own provider). The framework's own registration comment states the other honest limit: a host with no Redis gets the process-local, warn-once implementation, so "cross-replica" exclusion degrades back to per-replica (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:87-88).
IScheduledJob
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IScheduledJob.cs:36· Level 0 · interface
- What it is: the contract for a unit of recurring work driven by a cron schedule: a stable
Name, a defaultCronExpression, and anExecuteAsyncthat runs one occurrence. - Depends on: BCL only (
Task,CancellationToken). Executed by ScheduledJobRunner, persisted as ScheduledJobEntry rows, configured through SchedulerSettings and ScheduledJobOverrideSettings, and cron-parsed by Cronos (NuGet). - Concept introduced, recurring work as a first-class Application abstraction.
[Rubric §13, Observability & Operability]assesses whether operators can see and steer background work; a job here is a named row with a schedule, an outcome and a last error, not an anonymousTimer.[Rubric §7, Microservices Readiness]and[Rubric §29, Resilience]assess behavior under scale-out and partial failure, and the interface's own doc is where the hard rules are written down (IScheduledJob.cs:8-35), so read them as contract, not commentary:- Lifetime: jobs are resolved scoped, in a fresh DI scope per execution, exactly like a request. A job may take scoped dependencies (a unit of work, a repository, a command handler) and must hold no state between runs, because the previous instance is already disposed (
:9-14). - Single runner across replicas: every replica runs a scheduler, but an occurrence executes once, because the persistent job store hands out a claim lease per row (the outbox processor's claim idiom) and only the claim winner runs (
:16-21). A replica that dies mid-execution releases its claim implicitly when the lease expires. - Missed occurrences do not pile up: after an outage the job runs once and its next run is computed from the current instant, not from the backlog (
:23-29). Work that must not be skipped therefore has to be idempotent and range-driven, processing everything since the last successful run rather than relying on one run per tick. - Failures are recorded, not fatal: an exception from
ExecuteAsyncis caught, logged and stamped on the row as a failed outcome while the schedule advances and the loop survives; there is no retry inside an occurrence (:31-33).
- Lifetime: jobs are resolved scoped, in a fresh DI scope per execution, exactly like a request. A job may take scoped dependencies (a unit of work, a repository, a command handler) and must hold no state between runs, because the previous instance is already disposed (
- Walkthrough: line 44 declares
string Name { get; }, the stable identity that is also the primary key of the persisted row, so renaming it strands the old row and starts a new schedule, and two registered jobs must never share it (:38-43). Line 68 declaresstring CronExpression { get; }, a five-field expression (minute hour day-of-month month day-of-week) parsed by Cronos, with worked examples on:51-56. Two properties of that field are load-bearing: all times are UTC, never a local or configured zone, so a schedule never shifts, doubles or vanishes across a daylight-saving transition (:57-62), and the value is only the default, overridden per job byScheduler:Jobs:{Name}:Cronin configuration whenever that key is present (:63-66). Line 78 declaresTask ExecuteAsync(CancellationToken cancellationToken), whose token is cancelled on host shutdown; work that ignores it delays shutdown and can outlive its claim lease (:73-76). - Why it's built this way: ADR-074 records the design. Keeping the interface in Application (with no EF, no
IHostedService, no cron library type in its signature) is what lets a module declare recurring work without taking an Infrastructure dependency, and lets the runner, the persistence of job state and the claim protocol all stay replaceable. Registration is deliberately split in two:AddScheduledJobs(configuration)enables the runner once per host (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:37, registering ScheduledJobRunner throughTryAddEnumerableat:47-48so two callers cannot start two runners racing the same rows,:44-46), whileAddScheduledJob<TJob>()adds one job, scoped and accumulating (:72-78, rationale at:58-70). Registering the scheduler is not the same as turning it on: everything stays inert untilScheduler:Enabledis true (:31-35). - Where it's used: one implementation exists in the workspace today.
- The framework ships
AuditTrailCleanupJob(see AuditTrailCleanupJob), declared atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailCleanupJob.cs:47-54, named"audit-trail-cleanup"and scheduled"0 3 * * *", daily at 03:00 UTC (:63,67). It is registered byAddAuditTrailrather than byAddScheduledJobs(.../Infrastructure/DependencyInjection.cs:478), which keeps the trail and the scheduler independent features (:475-477). - MMCA.ADC no longer recovers interrupted AI-scoring passes with a scheduled sweep job:
SessionScoringSweepJobwas replaced by the ADR-114 internal commandConference.ScoreEventSessions.v1, whose handler runs at-least-once (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/DecisionSupport/ScoreEventSessions/ScoreEventSessionsInternalCommandHandler.cs:37), so an interrupted pass is picked up again by the framework's internal-command processor and its backoff/attempt ceiling (:25-28) rather than by a five-minute cron sweep. - The runner itself is switched on per host. Seven hosts call
AddScheduledJobs(builder.Configuration)today: ADC's three service hosts (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:360,.../MMCA.ADC.Engagement.Service/Program.cs:193,.../MMCA.ADC.Identity.Service/Program.cs:228), Store's three (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:94,.../MMCA.Store.Sales.Service/Program.cs:106,.../MMCA.Store.Identity.Service/Program.cs:102) and the reference app (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:79).
- The framework ships
- Caveats / not-in-source:
MMCA.Store/Sourceimplements noIScheduledJobof its own; its hosts enable the scheduler for the framework's retention job, which is exactly what the comment above those calls says ("The scheduled-job runner purges it past AuditTrail:RetentionDays",MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:102-106). Retention only happens in a host that enables both features: registering the trail without the scheduler records every change and purges nothing, leavingAuditTrail:RetentionDaysinert, which is what theAddAuditTraildoc warns about (.../Infrastructure/DependencyInjection.cs:450-456).
ICounterStore
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICounterStore.cs:23· Level 0 · interface
- What it is: the contract for atomic fixed-window counters, the substrate of every rate limit and brute-force throttle in the framework (login failure counts, registration and token-request throttles,
ICounterStore.cs:3-7). Three members: increment and read back, read without changing, and delete. - Depends on: BCL only (
Task<long>,TimeSpan,CancellationToken). Deliberately kept apart from ICacheService (ICounterStore.cs:5-7). Its two implementations live in Infrastructure: RedisCounterStore and the process-local InMemoryCounterStore, chosen the same way IDistributedLock chooses its implementation. - Concept introduced, a counter is not a cache entry.
[Rubric §11, Security]assesses whether brute-force and abuse limits actually hold; a limit built from a cachegetthensetloses increments under concurrency and lets the expiry drift, which is exactly the gap the type doc names (ICounterStore.cs:5-7): a counter needs an atomic increment and an expiry anchored to its first increment. The fixed window is the second half (:11-13): the increment that creates the counter sets its lifetime and later increments never extend it, so a caller who keeps hitting a counter cannot hold it open, and the allowance resets when the window the first increment opened ends.[Rubric §12, Performance & Scalability]: with Redis registered every replica counts against one number (:16-18).[Rubric §29, Resilience, Reliability & Business Continuity]: a Redis fault never fails the caller; the Redis store logs a warning at most once a minute and counts in-process until Redis answers again, so a limit keeps applying per replica instead of either failing every request or switching off (:18-20). - Walkthrough: line 23 declares the interface. Line 36 declares
Task<long> IncrementAsync(string key, TimeSpan window, CancellationToken cancellationToken = default), which adds one and returns the new value; only the increment that creates the counter sets its lifetime towindow(:27-29), and a zero or negativewindowthrowsArgumentOutOfRangeException(:35). Line 45 declaresTask<long> GetAsync(string key, CancellationToken cancellationToken = default), a read for a check that must run before the counted action (a registration limit read before the account is created, then incremented after,:38-40); it returns0when the counter does not exist or its window ended (:44). Line 54 declaresTask ResetAsync(string key, CancellationToken cancellationToken = default), which deletes the counter so the next increment starts a new window at one, the shape of a successful sign-in clearing its failure count (:47-49). - Why it's built this way: the type doc cites ADR-029 for the throttles it backs (
ICounterStore.cs:4). Splitting counters out of the cache contract keeps each contract honest: the cache can stay a get/set/invalidate surface, and the counter's atomicity and fixed-window expiry are stated once here rather than re-derived by every throttle. - Where it's used: registered singleton by
AddCaching(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:134-146), with RedisCounterStore when anIConnectionMultiplexeris resolvable (:131-137) and InMemoryCounterStore otherwise (:139); the comment above the registration ties the choice to the lock's (:125-127).- LoginProtectionService uses all three members: it increments the failure count (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:155), resets it on success (:184), and reads the registration count withGetAsync(:206) before incrementing it once the account exists (:233). - The three token services throttle requests with an increment and reset on use:
EmailConfirmationTokenService(.../Infrastructure/Auth/EmailConfirmationTokenService.cs:59,:123),PasswordResetTokenService(.../Infrastructure/Auth/PasswordResetTokenService.cs:69,:156) andSignInLinkTokenService(.../Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:61,:123). - MMCA.ADC's ClaimTicketHandler counts ticket-claim attempts per window of
ClaimAttemptWindowMinutes(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/UseCases/ClaimTicket/ClaimTicketHandler.cs:65-67).
- LoginProtectionService uses all three members: it increments the failure count (
- Caveats / not-in-source: a host with no Redis gets the process-local store, so every limit is enforced per replica rather than per deployment; whether a given deployment registers Redis is not determinable from source.
IInboxRecorder
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Events·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Events/IInboxRecorder.cs:20· Level 0 · interface
- What it is: the atomic half of the per-handler consumer inbox. It stages a handler's inbox row in the CURRENT scope's unit of work, unsaved, so the handler's own
SaveChangesAsynccommits it in the same transaction as its writes (IInboxRecorder.cs:3-5), and it revokes that row when the handler fails after the save. - Depends on: BCL only (
Guid,Task,CancellationToken). Called by ScopedIntegrationEventHandlerBase<TIntegrationEvent>, implemented by EfInboxRecorder, which writes InboxMessage rows beside the IInboxStore the broker consumer uses. - Concept introduced, recording "processed" in the same transaction as the processing.
[Rubric §6, CQRS & Event-Driven]assesses whether at-least-once delivery is made safe on the consumer side. An inbox row written in a separate transaction after the handler leaves a crash window between the two: the work committed but the row did not, and the redelivery runs the work again. Staging the row in the handler's own scope closes that window: a rollback discards both and no crash can land between them (IInboxRecorder.cs:7-9).[Rubric §29, Resilience, Reliability & Business Continuity]: the failure path is designed too. The row rides the scope's FIRST successful save, so a handler that saves and THEN fails has already committed it; revoking it is what makes "a failed handler always runs again" hold (MMCA.Common/Source/Core/MMCA.Common.Application/DomainEvents/ScopedIntegrationEventHandlerBase.cs:45-50). - Walkthrough: line 26 declares
void Stage(Guid messageId, string eventType, string consumer), whereeventTypeis the event's inbox name (its[EventName], else its short type name, kept for diagnostics,:24) andconsumeris the handler's inbox consumer name fromInboxConsumer.NameOf(:25). It is synchronous because it only adds to a context. Line 40 declaresTask RevokeAsync(Guid messageId, string consumer, CancellationToken cancellationToken), which deletes that consumer's row for that message if a save already committed it (:29-31). Its contract is set-based and idempotent: nothing staged, nothing committed, or a row already gone all delete zero rows (:32-33). Both members are inert outside a broker consume of that same handler and message (:15-17,:34), so the in-process dispatch of an integration event never writes inbox rows. - Why it's built this way: ADR-021 records the consumer inbox. The recorder is an Application-layer interface so the Application-layer base handler can stage a row without referencing EF Core, and it is optional: the base resolves it with
GetServiceand stages nothing when it is absent (IInboxRecorder.cs:14-15,ScopedIntegrationEventHandlerBase.cs:79-84). The revoke runs from a FRESH scope, never the failed handler's, because that context is exactly the one a failure can leave unusable (a rejected insert still tracked, an aborted transaction,ScopedIntegrationEventHandlerBase.cs:138-142, andIInboxRecorder.cs:31-32). - Where it's used: registered scoped by the broker messaging setup only inside
if (settings.IsInboxEnabled)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:141,149, rationale at:136-139), so with the inbox off there is nothing to resolve. ScopedIntegrationEventHandlerBase<TIntegrationEvent> callsStagein the scope it opens per delivery, beforeHandleScopedAsyncruns (ScopedIntegrationEventHandlerBase.cs:81-86), and on any failure, cancellation included (:96-102), resolves the recorder from a new scope and callsRevokeAsyncunder its own 5-second budget (RevokeBudgetSeconds,:63, used at:156-165) rather than the delivery's possibly-cancelled token. A revoke that itself fails is logged at Error and swallowed so the handler's original exception propagates (:168-174). The shipped implementation, EfInboxRecorder (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/EfInboxRecorder.cs:29-33), checks the current consume (:41,:69), adds anInboxMessageto the inbox data source's context (:49-55), and revokes with a set-basedExecuteDeleteAsyncfiltered on message id and consumer (:74-77). - Caveats / not-in-source: atomicity holds only when the handler writes to the SAME physical source the inbox lives in (the
Outbox:DataSource/Outbox:DatabaseNamepair); a handler writing elsewhere is back to two transactions, covered by the broker consumer's own record of the row after the handler returns (EfInboxRecorder.cs:18-22). Delivery stays at-least-once, so handlers must still be idempotent.
ITenantContext
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ITenantContext.cs:25· Level 0 · interface
- What it is: the scoped ambient contract for "which tenant is this scope running as": a nullable
TenantId, anIsResolvedflag for a single resolved tenant, anIsAllTenantsflag for a declared system scope, and two setters (SetTenant,SetAllTenants) of which a scope may settle on exactly one answer. - Depends on: BCL only. Implemented by TenantContext in Infrastructure, populated at the edge by TenantResolutionMiddleware, and consumed by the caching decorators in this group plus the persistence layer (G07). Configured through TenancySettings. Deliberately mirrors ICorrelationContext.
- Concept introduced, ambient scope state that fails closed.
[Rubric §11, Security]assesses whether data isolation is enforced structurally rather than remembered per query; every tenant-aware read filter, save interceptor and cache key reads this one object, so a handler cannot forget to scope itself.[Rubric §12, Performance & Scalability]: like the correlation id, the value is captured once at the edge and flows implicitly for the rest of the scope. The interesting design decision is the one the doc calls out (ITenantContext.cs:11-16): unlike the correlation id there is no generated fallback, and an unresolved tenant fails closed, reading no tenant-owned rows at all. A system operation that must see every tenant (a processor, a seeder, a retention sweep, an operator flow) has to say so explicitly withSetAllTenants, so "see everything" is always a decision in code and never the accident of a request that carried no tenant. The same holds for writes: a scope that resolved no tenant without that declaration may not write a tenanted row at all (ITenantContext.cs:55-56). - Walkthrough: line 31 declares
string? TenantId { get; }, null until a tenant is resolved and also null in an all-tenants scope, which names no single tenant (:28-29). Line 34 declaresbool IsResolved { get; }, true only for a single resolved tenant (:33). Line 40 declaresbool IsAllTenants { get; }(:36-39). Line 50 declaresvoid SetTenant(string tenantId): idempotent for the value already held (:43), it throwsArgumentExceptionon a null, empty or whitespace id (:46) andInvalidOperationExceptionwhen a different tenant was already resolved or the scope is an all-tenants scope (:47-49). Line 59 declaresvoid SetAllTenants(), which makes the scope a system scope that reads and writes every tenant's rows (:53): idempotent, throwingInvalidOperationExceptionwhen a tenant was already resolved (:58). Inserts in such a scope still need an explicit tenant on each row, because the tenant save interceptor refuses an untenanted one (:54-55), and a scope that resolved no tenant without the declaration may not write a tenanted row at all (:55-56). The rationale is on:19-22: one scope, one answer, because a scope whose answer changed mid-flight has already read rows under the previous one. The implementation (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/TenantContext.cs:14-81) seedsTenantIdin its constructor from the enclosing background hop's restored origin, so a scope opened while an outbox row, broker message or internal command is delivered starts with that hop's tenant (:20, doc at:10-12).IsResolvedisTenantId is not null(:26);SetAllTenantsthrows when a tenant is held, otherwise sets the flag (:34-43);SetTenantvalidates (:49), refuses to narrow an all-tenants scope (:51-58), assigns the first value (:60-64), returns quietly on a repeat (:68-71), and otherwise throws with a message naming both tenants (:73-79). - Why it's built this way: ADR-073 records the multi-tenancy model. Putting the contract in Application, not Infrastructure, is what lets the Application-layer caching decorators scope their keys without referencing EF Core: CachingCommandDecorator<TCommand, TResult> and CachingQueryDecorator<TQuery, TResult> both take it as an optional primary-constructor parameter defaulting to
null(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingCommandDecorator.cs:47and.../CachingQueryDecorator.cs:47), so a host that never resolves a tenant pays nothing. - Where it's used: registered scoped in
AddServices(), not inAddMultiTenancy(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:396). The comment above the line is the design statement (:391-395): the always-on registration costs one object per scope and removes a whole class of "works until someone forgets the opt-in" bug.AddMultiTenancy(configuration)(:359) binds and validates TenancySettings (:361-376); its doc states that it switches on resolution, not isolation, because the query filter, the TenantSaveChangesInterceptor and this context are always present (:337-348). The context is written at the edge by TenantResolutionMiddleware from a claim or a trusted header, and read in three places. DbContextFactory routes per tenant and wiresIsAllTenantsinto the context's accessor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:153), which theTenantquery filter reads asIsAllTenantsScope || TenantId == CurrentTenantId, so a scope with no tenant reads no tenant-owned rows (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:747-753, property at:166). Both caching decorators go throughTenantCacheKey.Scope, which prefixes the key witht:{tenantId}:only when a single tenant is resolved (.../UseCases/Decorators/TenantCacheKey.cs:37-40, called atCachingCommandDecorator.cs:106andCachingQueryDecorator.cs:59). AndAmbientOriginrestores a captured tenant onto the scope of an inbound hop throughSetTenant(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:310-327), throwing rather than running the hop under a different tenant the scope already resolved (:318-323), then publishes the scope's tenant for scopes opened inside the hop (:295). - Caveats / not-in-source: verified by source search in this pass,
MMCA.ADC/Sourcedoes not mentionITenantContextorSetAllTenants, and withinMMCA.Common/Sourceno code callsSetAllTenants()(only its declaration, its implementation and doc references). Multi-tenancy is a shipped, tested framework capability that ADC has not opted into; whetherMMCA.Store/Sourceuses it was not re-checked in this pass.
CqrsContractMismatchKind
MMCA.Common.Application ·
MMCA.Common.Application.UseCases·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/CqrsContractInspector.cs:9· Level 0 · enum
- What it is: the two-value classification of why a CQRS request and the handler written for it disagree. It is the
Kindcarried on every CqrsContractMismatch that CqrsContractInspector reports. - Depends on: nothing. It is a plain
int-backed enum with explicitly assigned members. - Concept introduced, naming the failure modes instead of formatting a string.
[Rubric §9, API & Contract Design]assesses whether the contracts a system publishes are checkable rather than conventional; giving the two disagreement kinds names is what lets a fitness test assert which problem it found, and what lets CqrsContractMismatch.Describe pick a message written for that specific problem rather than one generic sentence.[Rubric §15, Best Practices & Code Quality]: the members carry explicit values (ResultType = 0,HandlerKind = 1), so the enum's wire and log representation is pinned rather than positional. - Walkthrough: line 8 declares
public enum CqrsContractMismatchKind. Line 14 declaresResultType = 0: the request declared one result type through its ICommand<TResult> or IQuery<TResult> marker and its handler returns a different one (documented at:10-13). Line 20 declaresHandlerKind = 1: the request is declared as a command but handled by an IQueryHandler<in TQuery, TResult>, or declared as a query and handled by an ICommandHandler<in TCommand, TResult> (documented at:16-19). There is no "unknown" member; the switch inDescribestill carries a_arm (:48-49) so a future member cannot silently produce no message. - Why it's built this way: the two kinds are genuinely different bugs with different fixes. A
ResultTypemismatch means one of the two declarations is stale and the caller's expectations are already wrong; aHandlerKindmismatch means a request opted into the wrong side of CQRS entirely. Collapsing them into one "mismatch" would force whoever reads the failure to re-derive that distinction. - Where it's used: constructed only inside CqrsContractInspector (
CqrsContractInspector.cs:142forHandlerKind,:147forResultType), read byDescribe(:42-50), and asserted on in CqrsContractInspectorTests.
CrossServiceCacheKeys
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/CrossServiceCacheKeys.cs:24· Level 0 · class (static)
- What it is: the reserved key segment,
"xsvc:", that marks a cache entry every service sharing the cache must address identically: a record one service writes and another reads, such as the soft-deleted-user marker Identity writes and every service's middleware reads (CrossServiceCacheKeys.cs:3-7). - Depends on: nothing beyond the BCL (
ArgumentNullException,string.StartsWith). Read by HybridCacheService when it qualifies a key, and by CacheKeyNamespace and CacheKeyPrefixOptions, which resolve the namespace such a key lands in. - Concept introduced, one keyspace shared on purpose inside a deployment that is otherwise isolated.
[Rubric §11, Security]: a shared store qualifies every key with the host's own namespace (Cache:KeyPrefix, or the per-serviceApplication:Namespace), so two services never read each other's entries (CrossServiceCacheKeys.cs:10-12). That is correct for nearly every key and wrong for a revocation record: the writer and the reader would each address their own copy, and the reader would never see the write (:12-13), which would leave a deleted user's session or an ended view-as grant honored by every service except the one that wrote it. A key starting with the prefix is qualified with the cross-service namespace instead (:14-17), which defaults to the token audience (Jwt:Audience) because the services that accept one audience's tokens are exactly the services that must honor a revocation of them.[Rubric §15, Best Practices & Code Quality]: the opt-in is a named constant in the key itself, not a parallel API, so a caller marks a key cross-service by building it fromPrefixand every cache operation already routes it correctly. - Walkthrough: line 24 declares
public static class CrossServiceCacheKeys. Line 27 holdspublic const string Prefix = "xsvc:". Lines 32-36 hold the one method,IsCrossService(string key): it throws on a null key (:34) and returnskey.StartsWith(Prefix, StringComparison.Ordinal)(:35), an ordinal test so culture never changes which keyspace a key lands in. The consumer side is HybridCacheService's key builder (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/HybridCacheService.cs:390-399): a cross-service key is qualified with the cross-service namespace and gets no generation suffix (:442-444), while every other key takes the per-namespace generation suffix and the host's own namespace (:447-448). The namespace itself comes fromCacheKeyNamespace.CrossServiceFrom(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheKeyPrefix.cs:133-147): the configuredCache:CrossServiceKeyPrefix(CacheKeyPrefix.cs:47-55), otherwise the token audience, otherwise the host's own namespace. - Why it's built this way: the absence of a generation token is deliberate (
CrossServiceCacheKeys.cs:19-22). Generation tokens are per namespace, so if a cross-service key carried one, a prefix wipe in one service would move that service's copy away from everyone else's and hide the record from the others (HybridCacheService.cs:385-388). The cost is that such a key is not subject to prefix invalidation: it is removed by its exact key only. ADR-047 records the soft-deleted-user revocation this exists for, ADR-077 the cache substrate, and ADR-135 the per-application keyspace isolation this is the one exception to. - Where it's used: two key builders compose with
Prefixtoday. SoftDeletedUserCache builds{Prefix}user:deleted:{userId}(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUserCache.cs:77, rationale at:68), and ViewAsEndedMarker builds{Prefix}viewas:ended:{grantId}(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsEndedMarker.cs:41), because the store host writes it and every other service reads it (ViewAsEndedMarker.cs:36).IsCrossServiceis called only fromHybridCacheService.cs:392. - Caveats / not-in-source: the default keyspace is only shared when every service of a deployment is configured with the same
Jwt:Audience(or the same explicitCache:CrossServiceKeyPrefix,CacheKeyPrefix.cs:52-53); whether a given deployment's configuration does so is not determinable from source.
IAuditTrailWriter
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IAuditTrailWriter.cs:24· Level 0 · interface
- What it is: the one-method write surface for an event that changed no data (an access, such as a personal-data export), recorded on the same change-history trail IAuditTrailReader reads so it appears in that entity's history beside its recorded changes (
IAuditTrailWriter.cs:3-7). - Depends on: BCL only (
Task,CancellationToken) plus the solution-wideUserIdentifierTypealias for the actor (IAuditTrailWriter.cs:45). Implemented by AuditTrailWriter (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailWriter.cs:36-40), which writes the same AuditTrailEntry rows the AuditTrailSaveChangesInterceptor writes for changes to an IAuditedEntity. - Concept introduced, recording an access on a change trail without copying the data.
[Rubric §30, Compliance, Privacy & Data Governance]assesses whether a system can show who touched personal data, not only who changed it. The trail's automatic recording only sees saves, so this is the explicit counterpart for events a save never sees (IAuditTrailWriter.cs:10-12). It records the identifying columns only (entity type, key, operation, who and when) and carries no property name and no before or after value, so the access record can never become a copy of the data it describes (:12-14).[Rubric §3, Clean Architecture]: like the reader, the contract speaks in strings and an identifier with no EF type in its signature, so an Application-layer handler can record an access without knowing where trail rows live. - Walkthrough: line 24 declares the interface; lines 41-46 declare its single member,
Task RecordAsync(string entityType, string entityKey, string operation, UserIdentifierType? actorId, CancellationToken cancellationToken = default), which records one event and saves it (:27).entityTypeis the full CLR type name, the same value the reader is queried by (:29-32);entityKeyis the invariant string form of the primary key (:33);operationis the event's name (for exampleExported), recorded beside theAdded,ModifiedandDeletedrows the interceptor writes, at most 16 characters, the column width (:34-37); anullactorIdmeans the system (:38). The returned task completes once the row is saved, or immediately when the trail is off (:40). The implementation enforces the width rather than truncating: anoperationlonger thanMaxOperationLength(16,AuditTrailWriter.cs:43) throwsArgumentOutOfRangeException, because a name too long for the column is a programming error (AuditTrailWriter.cs:59-66). It returns without resolving a context whenAuditTrail:Enabledis false (:68-71), records nothing when the trail table is absent from the target model (:76-79), and otherwise adds oneAuditTrailEntrystamped with the UTC time, the ambient trace id and the context's current tenant (:82-91) and saves it as the actor's save (:93). - Why it's built this way: ADR-075 records the trail. The writer is always registered and inert until the trail is on (
IAuditTrailWriter.cs:17-19), so a handler can depend on it unconditionally rather than probing for an optional service. Its rows go to the database the reader reads (theDefaultsource of the engine named byAuditTrail:DataSource), so what is written is what the history endpoint shows (:19-21, resolved atAuditTrailWriter.cs:73-74). Because the context is the scope's shared one, the save flushes anything else pending on it, and inside an open transaction the row commits or rolls back with it (AuditTrailWriter.cs:26-29). - Where it's used: registered scoped by
AddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:137, comment at:134-136). Its one framework caller is ExportUserDataHandlerBase<TUser, TQuery>, which takes it as a primary-constructor parameter (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:64) and, once the export package is assembled and before it is returned, records anExportedAuditOperation("Exported",:80) row against the account's type and id with the caller as the actor (:138-144). A failure to write that record fails the export, so personal data is not released without its access record (:36-38). - Caveats / not-in-source: both consumer apps now take the writer. MMCA.ADC pins
MMCA.Common.Application1.333.0 (MMCA.ADC/Directory.Packages.props:148) and MMCA.Store pins 1.332.0 (MMCA.Store/Directory.Packages.props:30); ADC'sExportUserDataHandlerinjects anIAuditTrailWriterand passes it to the base (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:36-39), as does Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:46), so both record export access through this contract wheneverAuditTrail:Enabledis on. Whether a given deployment enables the trail is not determinable from source.
IAuditTrailReader
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IAuditTrailReader.cs:20· Level 1 · interface
- What it is: the one-method read surface over the recorded change history of a single entity: one page of changes, newest first.
- Depends on: AuditHistoryEntryDTO (its return payload,
MMCA.Common/Source/Core/MMCA.Common.Shared/Auditing/AuditHistoryEntryDTO.cs:12,usingatIAuditTrailReader.cs:1). Implemented by AuditTrailReader over the AuditTrailEntry rows written by the audit-trail save interceptor. - Concept introduced, shipping the read with an opt-in exposure.
[Rubric §30, Compliance, Privacy & Data Governance]assesses whether a system can answer "who changed this, and when"; the trail is that answer, and this is how an application asks.[Rubric §11, Security]assesses authorization placement, and the doc is explicit about the boundary it draws (IAuditTrailReader.cs:10-15): the framework ships the read plus an opt-in endpoint, and a host mounts that endpoint only by deriving a one-line controller from AuditHistoryControllerBase, which names the entity types it serves and is gated by theaudit:viewpermission. The gate sits on the base class itself (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/AuditHistoryControllerBase.cs:47, the constant atMMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/AdministrationPermissions.cs:46, see AdministrationPermissions), so a derived controller that forgets an attribute denies rather than exposes (AuditHistoryControllerBase.cs:43-44). A host that derives none exposes nothing, and a consumer stays free to wrap this reader in its own query instead.[Rubric §3, Clean Architecture]: the contract speaks in strings and DTOs with no EF type in its signature, so the Application layer can offer history without knowing where rows live. - Walkthrough:
IAuditTrailReader.cs:40-45declare the single member,Task<IReadOnlyList<AuditHistoryEntryDTO>> GetForEntityAsync(string entityType, string entityKey, int page = 1, int pageSize = 50, CancellationToken cancellationToken = default). The two identity parameters are string-typed on purpose, because they must match what the interceptor recorded:entityTypeis the full CLR type name (:25-28, for exampletypeof(Order).FullName) andentityKeyis the invariant string form of the primary key, with composite parts joined by|in the model's key order (:29-32). Paging is forgiving rather than validating, and it is bounded: apagebelow 1 is treated as 1, a page whose offset exceedsint.MaxValuerows returns an empty list (:33-36), andpageSizeis clamped to 1..500 (:37). The implementation does exactly that (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailReader.cs:55-56), with the 500 cap held in a privateMaxPageSizeconstant that mirrors the outbox administration read's own page cap (AuditTrailReader.cs:39-43). The offset is computed inlongand checked before it reaches the query (AuditTrailReader.cs:58-64), because(page - 1) * pageSizeoverflowsintfor a large page number and a wrapped negative offset would read as 0 on some engines, silently handing back the first page. Ordering is part of the contract, not an implementation detail (:17-18,23): newest change first, so the first page is the most recent activity, and the implementation makes that stable by orderingChangedOndescending with the row id descending as the tie-break (AuditTrailReader.cs:76-77). - Why it's built this way: ADR-075 records the trail. The interface exists at all so the read is testable and swappable, and it returns a DTO rather than the entity so the Application layer never handles a tracked row. The implementation is honest about a v1 limitation worth knowing before you build on it (
AuditTrailReader.cs:16-21): trail rows are written to whichever database holds the entity that changed, which is what makes the write atomic, but this reader queries exactly one of them, theDefaultdatabase of the engine named byAuditTrail:DataSource(resolved atAuditTrailReader.cs:66-67). For a monolith, where every source collapses ontoDefault, that is the whole trail; for a database-per-module host it is only the modules living in the default database. - Where it's used: registered scoped by
AddAuditTrail(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:127), which is opt-in per host: a host that never calls it has no implementation to resolve (IAuditTrailReader.cs:6-7). The reader returns an empty list rather than throwing when the trail table is absent from the model (AuditTrailReader.cs:69-72, rationale at:26-28), so registering the feature before flippingAuditTrail:Enabledis safe. Its framework caller is AuditHistoryControllerBase, which takes the reader in its constructor (AuditHistoryControllerBase.cs:69) and passes the served type'sFullNameasentityType(AuditHistoryControllerBase.cs:124). MMCA.ADC derives one such controller per module database: AuditHistoryController (Conference), AuditHistoryController (Engagement) and AuditHistoryController (Identity), because the reader reads only the host's Default database (AuditHistoryControllerBase.cs:41-43). - Caveats / not-in-source: whether MMCA.Store mounts the endpoint is not covered by this part's usage evidence, which lists only Common and ADC sites.
CqrsContractMismatch
MMCA.Common.Application ·
MMCA.Common.Application.UseCases·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/CqrsContractInspector.cs:32· Level 1 · record (sealed)
- What it is: one disagreement between a request's declared CQRS contract and the handler written for it, carrying both types, both result types, and the CqrsContractMismatchKind that says which kind of disagreement it is. Its
Describe()renders it as a single line fit for a test-failure message. - Depends on: CqrsContractMismatchKind; BCL
System.Typefor its four type-valued members. Produced by CqrsContractInspector. - Concept reinforced, the finding as a value, not a string.
[Rubric §14, Testability]assesses whether a check produces something a test can assert precisely on; keepingRequestType,HandlerType,DeclaredResultTypeandHandlerResultTypeasTypevalues (rather than pre-formatted text) is what lets CqrsContractInspectorTests assertm.DeclaredResultType == typeof(Result<int>)instead of matching on a substring.Describe()is then a presentation method layered on top, not the finding itself.[Rubric §15, Best Practices & Code Quality]: the positional record gives value equality and a readable constructor for free, which is why a mismatch can be compared and de-duplicated without any hand-written members. - Walkthrough: lines 31-36 declare the positional record
public sealed record CqrsContractMismatch(Type RequestType, Type HandlerType, Type DeclaredResultType, Type HandlerResultType, CqrsContractMismatchKind Kind), each parameter documented at:26-30. Lines 42-50 hold the sole member,Describe(), a switch expression overKindwith a message written for each case: theHandlerKindarm (:44-45) explains the rule it broke, that anICommandmarker needs anICommandHandlerand anIQuerymarker needs anIQueryHandler; theResultTypearm (:46-47) names the declared type and the returned type side by side; and the discard arm (:48-49) is the safety net for a future member. Every message usesType.Name, notFullName, because these lines are read in a test runner's output. - Why it's built this way: a fitness test that fails with "3 mismatches found" teaches nobody. Making the type carry the whole finding, and making it responsible for its own one-line rendering, means the assertion (
mismatches.Should().BeEmpty()) can stay trivial while the failure message stays specific. - Where it's used: constructed at
CqrsContractInspector.cs:141-142and:146-147, returned asIReadOnlyList<CqrsContractMismatch>fromFindContractMismatches(:83), and asserted on in CqrsContractInspectorTests.
IEventUpcaster
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Events·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Events/IEventUpcaster.cs:28· Level 2 · interface (plus its typed generic sibling in the same file)
- What it is: the contract for converting one retired integration-event contract into its successor, so handlers are written once against the newest shape while older messages (queued at the broker, or sitting unprocessed in an outbox written before the upgrade) keep being delivered. The file declares two interfaces: the non-generic
IEventUpcasterthe framework resolves and indexes by (:28), and the typedIEventUpcaster<in TSource, out TTarget>application code actually implements (:67). - Depends on: IIntegrationEvent (
usingat:2) as the type of both ends of the conversion, andSystem.Diagnostics.CodeAnalysis.SuppressMessage(BCL). Composed by IEventUpcasterRegistry and registered throughAddEventUpcaster<TSource, TTarget, TUpcaster>(). - Concept introduced, event-schema evolution by additive versioning instead of in-place reshaping.
[Rubric §6, CQRS & Event-Driven]assesses whether published event contracts can change without breaking subscribers, and[Rubric §9, API & Contract Design]assesses versioning of the contracts a system publishes. The policy behind this type is that a breaking event-shape change (a renamed, removed or retyped field) is a new event type plus a consumer-side upcaster, never a silent edit of an existing type (ADR-010); this interface plus its registration extension point is how that policy is actually expressed in code (ADR-090, cited at:15-19). The teaching point for a reader new to the pattern: upcasting is a read-side concern. Producers are never asked to publish two shapes, and handlers are never asked to accept two shapes. The conversion happens once, at the boundary between "what arrived" and "what the handlers are written for".[Rubric §7, Microservices Readiness]also applies, because a broker in front of independently-deployed services is exactly the environment where producer and consumer versions diverge for a while.[Rubric §15, Best Practices & Code Quality]: a chain of small pure functions is deletable in the order it was added, which is why the registration docs describe the retirement path (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Extensibility.cs:74-78). - Walkthrough, taking the two interfaces in the order the framework sees them.
- The non-generic
IEventUpcaster(:28) declares three members:Type SourceType { get; }(:31), the retired contract it reads;Type TargetType { get; }(:34), the successor it produces; andIIntegrationEvent Upcast(IIntegrationEvent integrationEvent)(:41). This is the shape the registry indexes by and walks chains with, so nothing in the framework needs to know the closed generic types. - The typed
IEventUpcaster<in TSource, out TTarget> : IEventUpcaster(:67) is what an application implements. Both parameters are constrainedclass, IIntegrationEvent(:68-69), and the variance annotations (in/out) are the natural ones for a converter. Its whole trick is default interface implementations:SourceType => typeof(TSource)(:72),TargetType => typeof(TTarget)(:75), and an explicitIIntegrationEvent IEventUpcaster.Upcast(...)that downcasts and forwards to the typed overload (:85-86). An implementer therefore writes exactly one method,TTarget Upcast(TSource integrationEvent)(:82), and gets the non-generic surface for free. - The
[SuppressMessage]on CA1033 (:63-66) documents why: a default interface implementation of an inherited member can only be written as an explicit implementation, so there is no non-explicit form to offer child types. - Map payload fields only (
:21-26and:58-61). The framework preserves the envelope: after every hop the registry stampsMessageIdandDateOccurredfrom the pre-hop instance onto the upcasted one, so consumer-side inbox deduplication keeps working on the id the producer published. An upcaster that copies them itself is harmless (the stamp is idempotent) and one that forgets is still correct.
- The non-generic
- Why it's built this way: splitting the non-generic index surface from the typed authoring surface is what lets one registry hold heterogeneous upcasters in a single
Dictionary<Type, IEventUpcaster>while implementers still write strongly typed code with no casts. Registration names both contracts explicitly,services.AddEventUpcaster<TOld, TNew, TUpcaster>()(.../Application/DependencyInjection.cs:551-558), so the compiler checks the shape at the registration site rather than leaving a mismatch to fail on the first message (:534-536); implementations are registered singleton throughTryAddEnumerablebecause they are pure functions (:556). Chains compose: registering V1 to V2 and V2 to V3 delivers a V1 message to the V3 handler (:539, andIEventUpcaster.cs:56). - Where it's used: composed by IEventUpcasterRegistry and thereby reached from both delivery paths, the in-process DomainEventDispatcher and the broker-side UpcastingIntegrationEventConsumer<TEvent>. Two architecture fitness rules police the shape across every repo, living once in the shared rules package:
EventUpcastersHaveUniqueSourceTypes(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Contracts/ArchitectureRules.Upcasters.cs:14), because with two upcasters reading one type the contract a handler receives would depend on DI registration order, andEventUpcastersIncreaseSchemaVersion(:28), which reads theSchemaVersionoff both contracts and fails when the target is not strictly higher (:34-47, with a missing or non-int version deliberately left to a different rule,:37-38). The rules match the interface by name and arity (an ordinal comparison against the runtime name ofIEventUpcasterwith generic arity 2,:82-83) so the rule library keeps its no-compile-dependency idiom.SchemaVersionitself is thevirtual inton BaseIntegrationEvent that defaults to 1 (MMCA.Common/Source/Core/MMCA.Common.Domain/DomainEvents/BaseIntegrationEvent.cs:32). - Caveats / not-in-source: verified by source search, no
Source/tree in the workspace contains anIEventUpcasterimplementation today, in the framework or in MMCA.ADC, MMCA.Store or MMCA.Helpdesk; the only two mentions outside the interface file are the generic constraint onAddEventUpcaster(.../Application/DependencyInjection.cs:554) and the interface's own declaration. Every implementation is a test fixture. The mechanism is fully built and tested and has not yet had to be used on a real contract; the doc comment on the framework's own OutputCacheEvictionRequested records this as the shape a future V2 would take (MMCA.Common/Source/Core/MMCA.Common.Domain/IntegrationEvents/OutputCacheEvictionRequested.cs:16-26).
IEventUpcasterRegistry
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Events·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Events/IEventUpcasterRegistry.cs:24· Level 2 · interface
- What it is: the composed view of every registered IEventUpcaster. It answers three questions: does anything upcast this type, what is the newest contract this type ends up as, and give me this instance converted to that contract, walking the whole chain.
- Depends on: IIntegrationEvent (
usingat:1) and IEventUpcaster. Implemented by EventUpcasterRegistry (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/EventUpcasterRegistry.cs:30). - Concept introduced, the empty-registry identity default.
[Rubric §12, Performance & Scalability]assesses how an optional capability is threaded through a pipeline without every call site having to test for its presence. The registry is registered unconditionally byAddApplication()(.../Application/DependencyInjection.cs:41, comment at:37-40): with no upcasters registered it is an empty registry whose operations are the identity function, so both delivery paths can depend on it without a null check or a feature flag (ADR-090).[Rubric §15, Best Practices & Code Quality]and[Rubric §13, Observability & Operability]both apply to the failure model: a misregistration is a programming error, so it throws at composition time naming the offenders rather than returning aResult(EventUpcasterRegistry.cs:14-20), and a dedicated hosted service makes that happen at host start rather than on the first message. - Walkthrough: three members on the interface, and the implementation behind each is worth reading.
bool HasUpcasterFor(Type eventType)(:31) is a dictionary probe (EventUpcasterRegistry.cs:85-90).Type ResolveTerminalType(Type eventType)(:39) returns the newest contract the type upcasts to, or the type itself when nothing claims it (EventUpcasterRegistry.cs:93-98). It is a precomputed lookup, not a walk:BuildTerminalTypesresolves every chain once in the constructor (:81, method at:133-161), because the chain graph is static once DI is built.IIntegrationEvent UpcastToTerminal(IIntegrationEvent integrationEvent)(:48) applies every hop and preserves the envelope at each one (EventUpcasterRegistry.cs:101-123). Two details in the loop repay attention: it advances by the upcaster's declaredTargetTyperather than the runtime type of what was returned, which the constructor's acyclicity check is what bounds, and anullreturn from an upcaster throws with the offender named (:112-114).- Validation is constructor-time (
EventUpcasterRegistry.cs:50-82). A self-mapping upcaster (:61) and two upcasters claiming one source (:67) are collected into anoffenderslist (:55), so a misconfigured host sees all the problems at once rather than one per restart, then a singleInvalidOperationExceptionis thrown (:74-79). Cycles are caught separately inBuildTerminalTypesby walking each chain with avisitedset and reporting the chain in order (:139-155); a repeated type is definitely a cycle and not a diamond, because the duplicate-source check already made the graph functional. - Envelope preservation (
EventUpcasterRegistry.cs:169-179) readsMessageIdandDateOccurredoff the pre-hop instance and writes them onto the upcasted one through cachedPropertyInfohandles, held in a staticConcurrentDictionarykeyed by the produced type (:36) so a chain pays the reflection lookup once per contract. Both properties areinit-only on the domain-event base, which reflection can still set, and a non-writable property is simply skipped (Writable,:181-182).
- Why it's built this way: ADR-090. Making envelope preservation the registry's job rather than the author's is the load-bearing choice: it means consumer-side inbox deduplication stays keyed on the id the producer published by construction, so no upcaster author can break deduplication by forgetting to copy a field they were never asked to think about (
EventUpcasterRegistry.cs:22-27). Precomputing terminal types and caching envelope reflection keeps the per-message cost to dictionary lookups and delegate calls. - Where it's used: registered singleton by
AddApplication()(.../Application/DependencyInjection.cs:41) and consumed by both delivery paths.- In-process: DomainEventDispatcher holds it as a
Lazy<IEventUpcasterRegistry?>resolved withGetService(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/DomainEventDispatcher.cs:32-33) and runs the integration branch through it before resolving handlers, so the handlers invoked are the ones written against the newest type (:58-62). - Broker-side: UpcastingIntegrationEventConsumer<TEvent> takes it as a constructor dependency (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastingIntegrationEventConsumer.cs:30-31) and dedups on the original message id before any upcasting (:56-70), then probesHasUpcasterForand converts (:72-79). It is registered per retired type withRegisterUpcastedIntegrationEventConsumer<TEvent>()on the broker consumer builder (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerConsumerBuilder.cs:40), whose doc is explicit that you must never also register the plain IntegrationEventConsumer<TEvent> for the same type (:33-34). The builder enforces it: a second registration of the same event type or event name, of either kind, throwsInvalidOperationException(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:50-57). - Startup: EventUpcasterStartupValidator is an
IHostedServicewhose entire job is to resolve the registry and touch one member, turning the constructor validation into a host-start failure (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/EventUpcasterStartupValidator.cs:20,23-30). It is registered byAddInfrastructurethroughTryAddEnumerable(.../Infrastructure/DependencyInjection.cs:175-176) so several modules calling it do not run the validation several times (:171-174).
- In-process: DomainEventDispatcher holds it as a
- Caveats / not-in-source: because no host registers an upcaster today (see IEventUpcaster), every production resolution of this type is the empty-registry identity path;
UpcastToTerminalreturns its argument andResolveTerminalTypereturns its argument. The chain-walking, cycle detection and envelope preservation described above are exercised only by tests at present.
CqrsContractInspector
MMCA.Common.Application ·
MMCA.Common.Application.UseCases·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/CqrsContractInspector.cs:73· Level 2 · class (static)
- What it is: a reflection-only inspector that pairs request types carrying the opt-in ICommand<TResult> / IQuery<TResult> markers with the handlers written for them, and reports every disagreement as a CqrsContractMismatch. It is built to be called from an architecture fitness test.
- Depends on: ICommand<TResult>, IQuery<TResult>, ICommandHandler<in TCommand, TResult>, IQueryHandler<in TQuery, TResult>, CqrsContractMismatch, CqrsContractMismatchKind. Externally,
System.Reflectiononly:Assembly.GetTypes,Type.GetInterfaces,GetGenericTypeDefinition,GetGenericArguments. No IL reading, no third-party fitness library. - Concept introduced, an architecture fitness check written as a library function.
[Rubric §34, Architecture Governance & Documentation]assesses whether architectural rules are enforced mechanically rather than by review habit; this type is the mechanism for one specific rule (a request's declared result type must equal its handler's), packaged so any consumer repo can enforce it in three lines: callFindContractMismatchesover its module assemblies and fail when the list is non-empty (:59-65).[Rubric §14, Testability]assesses how easy correctness is to assert: returning a list of values rather than throwing means the caller chooses the assertion and the failure message.[Rubric §15, Best Practices & Code Quality]: the check is gradual by construction. Requests carrying no marker are ignored entirely, so adopting the markers is per command and a repo with zero adoption sees an empty list rather than a wall of failures. That is the design decision that makes an opt-in contract check shippable into an existing codebase at all. - Walkthrough: line 72 declares
public static class CqrsContractInspector. The public surface is one method,FindContractMismatches(params IEnumerable<Assembly> assemblies)(:83), whoseparamscollection lets a caller list module assemblies inline or pass an existing sequence. It null-guards (:85), then builds its candidate set: every type across the assemblies that is not abstract, not an interface and not an open generic type definition (:89-91). That last filter is load-bearing and is documented at:66-70: the framework's own decorators (and any generic handler base) implementICommandHandler<,>with a type parameter in the request position, so inspecting them would compare a type parameter against a result type.InspectHandler(:101-120) walks each candidate's interfaces, keeps only the closedICommandHandler<,>andIQueryHandler<,>ones (:105-112), and pulls the request and result type arguments (:114).Compare(:122-148) is the rule itself:FindMarkerlooks forICommand<>andIQuery<>on the request (:128-129, helper at:154-163); the marker of the handler's own kind ismatchingand the other isopposite(:131-132). Ifmatchingis null, a nulloppositemeans the request simply never opted in and is skipped, while a non-nulloppositeis a genuine pairing bug reported asHandlerKind(:134-142). Otherwise a marker exists and the check is a single type equality:matching == handlerResultType, else aResultTypemismatch (:144-147). One robustness detail closes it out:GetLoadableTypes(:169-179) catchesReflectionTypeLoadExceptionand degrades to the types that did load, so one missing transitive reference cannot take down the whole scan. - Why it's built this way: the compiler already checks that a handler call site matches the handler's signature; what it cannot check is whether the handler written for a command is the one the command's authors and callers assume. A reflection pass over closed handler interfaces is the cheapest way to close that gap without introducing a runtime mediator or attributes. No ADR governs this type; its rationale is stated in its own remarks (
:58-70). - Where it's used: CqrsContractInspectorTests exercises all seven behaviors (mismatch detection, readable description, agreeing handlers, unmarked requests, the wrong-handler-kind case, an assembly with no handlers, a null argument, and the open-generic-decorator skip) against fixtures declared in the same file (
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/UseCases/CqrsContractInspectorTests.cs:88-126). - Caveats / not-in-source: verified by source search, no architecture fitness test in MMCA.Common, MMCA.ADC, MMCA.Store or MMCA.Helpdesk calls
FindContractMismatchestoday; the only caller in the workspace is the framework's own unit test. Combined with zero marker adoption (see ICommand<TResult>), the inspector is a shipped and tested capability that currently guards nothing in a consumer repo.
IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Mapping·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityDTOProjector.cs:45· Level 4 · interface
- What it is: an opt-in, one-method contract that rewrites an entity
IQueryableinto a DTOIQueryable, so the database returns only the columns the DTO actually has instead of whole entity rows that are mapped afterwards. - Depends on: AuditableBaseEntity<TIdentifierType> and IBaseDTO<TIdentifierType> as generic constraints (
IEntityDTOProjector.cs:46-48,usings at:1-2). It is the pushdown counterpart of IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>, consumed by EntityQueryService<TEntity, TEntityDTO, TIdentifierType> and executed through IEntityQueryPipeline. Implementations are typically Mapperly-generated (Riok.Mapperly, NuGet). - Concept introduced, projection pushdown as an optional, additive read path.
[Rubric §12, Performance & Scalability]assesses whether reads pay for data they do not return; the doc states the two costs the entity path incurs (IEntityDTOProjector.cs:9-16): the query must select whole entities (every column, plus a JOIN per include the DTO happens to flatten), and every materialized row is mapped in .NET afterwards. A projector removes both by making the provider select the DTO's columns directly.[Rubric §8, Data Architecture]assesses how much shaping is pushed to the database. The design point worth internalising is that this is additive, never required: registering one for an entity is what switches that entity's list reads onto the projected path, and nothing breaks when none is registered because the query service falls back to materialize-then-map. The remarks then bound what a projection can express (:36-41): it is an expression tree the provider must translate, so no instance sub-mappers, no custom mapping methods (Use = nameof(...)), no after-map hooks, nothing that would have to run in .NET on a materialized object. A DTO whose shape needs any of those simply does not get a projector, and its reads keep using the mapper. - Walkthrough: line 51 declares
public interface IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>, constrained to an auditable entity, anIBaseDTO, and anotnullkey (:52-54). Line 62 declares the single member,IQueryable<TEntityDTO> ProjectTo(IQueryable<TEntity> source), whose contract is stated in two halves: the input is an entity queryable already filtered, sorted, and paged (:60), and the output must still be a translatable queryable, so an implementation must not materialize insideProjectTo(:56-58). The doc carries a worked example (:23-35) of the idiomatic shape: a Mapperly[Mapper]static partial class exposingProjectToDTO, wrapped by a smallsealed classimplementing this interface. The last remark is the correctness obligation (:42-46): a projector MUST produce the same values as the entity's mapper for the same row, because the two paths are chosen by registration, so a divergence would make a response depend on whether a projector happened to be registered. The doc says to pin the equivalence with a test, and the framework's own projector does exactly that. - Why it's built this way: ADR-055 records the optional projector on the read contract. The interesting mechanical detail is how "optional" is expressed in DI, because
Microsoft.Extensions.DependencyInjectionhas no notion of an optional dependency: a single constructor naming an unregistered service fails to resolve, default value or not. EntityQueryService<TEntity, TEntityDTO, TIdentifierType> therefore declares a second, longer constructor that takes the projector (EntityQueryService.cs:73-81, rationale at:57-64); the container picks the longer one when a projector is registered and the shorter one when it is not, with no ambiguity because one parameter set is a strict superset of the other, and existing subclasses keep compiling untouched. - Where it's used: discovered by convention.
ScanModuleApplicationServices<TAssemblyMarker>()scans a module assembly forIEntityDTOProjector<,,>and registers each as itself plus its interfaces, scoped, beside the DTO mappers (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:63, with the opt-in rationale in the comment at:60-62), so a module only has to write the projector class. At read time EntityQueryService<TEntity, TEntityDTO, TIdentifierType> holds it as a nullableDTOProjectorproperty (EntityQueryService.cs:88) and takes the projected branch only whenCanProjectis true (:346, branch at:393-403, predicate at:717-720). That predicate is three conditions: a projector is registered, the caller did not ask for tracking, and the query has no unsupported (cross-source) includes, because those are loaded row by row after materialization by the navigation populator and a projection has no rows to hand it (:706-710). Field shaping deliberately does not disqualify, because shaping runs after materialization over whatever object the pipeline produced (:713-714). The framework ships one worked implementation, PushNotificationDTOProjector (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/DTOs/PushNotificationDTOProjector.cs:23-29), registered explicitly by the notification module (.../Notifications/DependencyInjection.cs:50-52). - Caveats / not-in-source: verified by source search, neither MMCA.ADC nor MMCA.Store registers a projector today; outside the framework's own notification projector the only implementation in the workspace is MMCA.Helpdesk's
TicketDTOProjector(MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/Tickets/DTOs/TicketDTOProjector.cs:38-47), which exists as the reference-app demonstration. Every list read in both production apps therefore still runs the materialize-then-map path. The equivalence obligation is also a convention, not a compiler rule: the framework's projector documents an enum-to-string divergence it had to inline by hand (the entity'sStatusis an enum, the DTO's is a string, and the instance mapper'sUse = nameof(MapStatusToString)is not expressible in an expression tree, so the projection inlines a conditional that the provider renders as a SQLCASE,PushNotificationDTOProjector.cs:15-22) and pins it with a test, but nothing stops a new projector from quietly disagreeing with its mapper.
IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Mapping·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityDTOMapper.cs:79· Level 4 · interface
- What it is: the contract that applies an incoming update request onto an already-loaded aggregate by calling that aggregate's own guarded mutation methods, returning a bare Result. It is the write-side twin of IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType>: the mapper owns "request to a new aggregate", the applier owns "request onto an existing aggregate" (
IEntityDTOMapper.cs:62-69). - Depends on: AuditableBaseEntity<TIdentifierType> as a generic constraint and Result as its return type (
usings atIEntityDTOMapper.cs:1-3). Consumed by UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest> and, for verb-scoped updates, by UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType>'s applier-typed sibling. Its widened cousin for updates that need the whole command is IEntityUpdateCommandApplier<TEntity, TUpdateRequest, TIdentifierType, in TCommand>. - Concept introduced, keeping the generic write handler out of the domain's business.
[Rubric §4, DDD]assesses whether invariants live in the aggregate rather than in application services; this contract is the mechanism that keeps them there. The framework ships one generic update handler that owns the boring, identical parts of every update (load the aggregate, honour the optimistic-concurrency token, save), and the applier owns the one part that is genuinely per-aggregate: calling the guarded mutation method. Nothing in the framework writes a property (.../Application/DependencyInjection.cs:291-297).[Rubric §1, SOLID]: a one-method interface with three type parameters is the smallest possible extension point for "how does this request change this aggregate", and it is what makes the handler open for extension and closed for modification.[Rubric §5, Vertical Slice]: each applier lives beside its request and its command in the module'sUseCases/{Verb}folder, so a verb is one directory rather than an edit to a shared switch. - Walkthrough: line 79 declares
public interface IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>, constrained to an auditable entity and anotnullkey (:80-81); note thatTUpdateRequestcarries no constraint, unlike the create side'sICreateRequest. Line 91 declares the single member,Task<Result> ApplyAsync(TEntity entity, TUpdateRequest request, CancellationToken cancellationToken = default), and its two contract halves are on:83-90: theentityhanded in is the loaded, tracked aggregate, and the return is the aggregate's own Result, so a refused invariant stops the write before it is saved. The return type is the design decision worth pausing on (:70-74): the applier answers with a bareResultrather than a new entity, because a successful apply has already mutated the tracked instance in place, and a failure must leave it untouched so nothing reaches the database. A real implementation is therefore three lines of delegation, for exampleMMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Products/UseCases/Rename/ProductRenameApplier.cs:16-22, which null-checks and returnsentity.Rename(request.Name), or the widerMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Activities/UseCases/Update/ActivityUpdateApplier.cs:20-34, which forwards eight request fields intoActivity.Update. - Why it's built this way: putting the mutation behind this contract is what lets the framework ship one generic update handler at all. UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest> takes the applier as a constructor dependency (
MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/UpdateEntityHandler.cs:48-50) and its wholeMutateAsyncoverride is one line,updateApplier.ApplyAsync(entity, command.Request, cancellationToken)(:91); the handler keeps loading, theRowVersionhook (:76-80) and the save, while the aggregate keeps its invariants and the domain events it raises (:29-35). The same file carries a five-parameter overload that resolves the applier by its concrete type (:115-127, mutation at:161), which is what lets one aggregate expose several verbs over one request DTO: two verbs become two commands, two handlers and two appliers, with nothing duplicated but the registration line (.../Application/DependencyInjection.cs:374-377). - Where it's used: discovered by convention and registered in three ways.
ScanModuleApplicationServices<TAssemblyMarker>()scans a module assembly forIEntityUpdateApplier<,,>and registers each as itself plus its interfaces, scoped, beside the request mappers (.../Application/DependencyInjection.cs:223-227, rationale at:219-222), so a module only writes the applier class.AddEntityCrud<...>()then wires the standard update verb, mappingUpdateEntityCommandtoUpdateEntityHandler(:329,342-343), andAddEntityUpdateVerb<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest, TApplier>()wires an extra verb, constrained onwhere TApplier : class, IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>(signature:391, constraint:395, registration:400-401, with the two-verb inventory example in its doc at:384-388). Fifteen implementations exist across theSource/trees: 11 inMMCA.Store/Source(threeCustomerverbs, fourProductverbs, twoCategoryverbs, and theIncreaseInventoryApplier/DecreaseInventoryApplierpair over oneInventoryItemAdjustRequest), 3 inMMCA.ADC/Source(SponsorUpdateApplier,ActivityUpdateApplier,ConferenceCategoryUpdateApplier) and 1 inMMCA.Helpdesk/Source(TicketUpdateApplier). - Caveats / not-in-source: the framework itself ships no implementation; every applier is application code, which is the point.
TUpdateRequestbeing unconstrained means nothing in the type system stops an applier being declared over a create request DTO, so the create/update symmetry the interface pair suggests is a convention here rather than a compiler rule. An applier that mutates the aggregate and then returns a failure would break the "a failure must leave it untouched" contract, and nothing enforces that either: it is a documented obligation on the implementer (IEntityDTOMapper.cs:70-74).
ICommand<TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Contracts·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommand.cs:31· Level 0 · interface (marker, empty)
- What it is: an opt-in marker a command record can implement to declare the result type its handler produces, so the request and its ICommandHandler<in TCommand, TResult> can be paired by a check instead of by convention alone. It has no members: the entire payload is the
TResulttype argument. - Depends on: nothing at runtime.
System.Diagnostics.CodeAnalysis.SuppressMessage(BCL) is applied to it. Read by CqrsContractInspector and paired against ICommandHandler<in TCommand, TResult>; the declared type is normally Result orResult<T>. - Concept introduced, the phantom type parameter. A phantom type parameter appears in a type's signature but in none of its members: nothing stores a
TResult, nothing returns one. Its only job is to travel with the type so a later reader (here, reflection) can recover it.[Rubric §9, API & Contract Design]assesses whether contracts are explicit and machine-checkable rather than agreed by naming convention; declaringICommand<Result<int>>on the command is what turns "the handler for this command returns what everybody assumes it returns" into a statement a test can verify.[Rubric §15, Best Practices & Code Quality]: the analyzer that flags unused type parameters (SonarS2326) is suppressed with a written justification rather than worked around (ICommand.cs:27-30), and the justification is the teaching text: consumingTResultin a member would force every command DTO to implement a method it has no business owning.[Rubric §15, Best Practices & Code Quality]: the marker is purely additive (:13-19), so adoption is per command at whatever pace suits the module, and a command that does not implement it behaves identically. - Walkthrough: line 31 is the whole declaration,
public interface ICommand<TResult>;, in the semicolon-body form the framework uses for every member-less interface. Lines 27-30 carry theSuppressMessageattribute described above. The doc comment does the rest of the work::13-19states the additive guarantee (handlers keep implementingICommandHandlerexactly as before, nothing in the registration or decorator pipeline reads the marker), and:20-25states the pay-off, that once a command declares its result type a fitness test can catch the "handler returnsResult<int>but every caller expectsResult<Guid>" drift. - Why it's built this way: this codebase does not route commands through a mediator, so nothing at runtime needs the result type; handlers are injected as closed
ICommandHandler<TCommand, TResult>and the compiler already checks the call site. What the compiler cannot check is whether the right handler was written for a command, because a second handler over the same command with a different result type compiles fine. The marker plus a reflection pass closes that gap without adding a runtime dispatcher. No ADR governs the marker; the rationale lives in the XML docs on the interface itself. - Where it's used: read only by CqrsContractInspector (
CqrsContractInspector.cs:129), which looks for exactly this open generic definition. - Caveats / not-in-source: verified by source search, no command in
MMCA.ADC/Source,MMCA.Store/SourceorMMCA.HelpdeskimplementsICommand<TResult>today. The only implementers in the workspace are the framework's own test fixtures (CqrsContractInspectorTests, for exampleAgreeingMarkedCommandandDriftedMarkedCommandatMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/UseCases/CqrsContractInspectorTests.cs:88and:89). It is a shipped, tested extension point with zero production adoption, which is exactly the state the inspector's own docs anticipate: a repo with no adoption sees an empty mismatch list rather than a wall of failures.
ICommandHandler<in TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Contracts·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommandHandler.cs:9· Level 0 · interface
- What it is: the CQRS command-handler contract: one method,
HandleAsync, that accepts a mutation command and returns a result, typically Result orResult<T>. - Depends on: BCL only (
Task,CancellationToken). Implementations return types fromMMCA.Common.Shared(Result andResult<T>, with failures described by Error). - Concept introduced, the CQRS command side.
[Rubric §6, CQRS & Event-Driven]assesses the separation of mutating writes from side-effect-free reads; commands express intent to change state (create, update, delete) and return a Result.[Rubric §1, SOLID]: a one-method interface gives each handler a single responsibility and, via contravariance, clean substitutability. Implementations are auto-discovered by an assembly scan (ScanModuleApplicationServicesscans forICommandHandler<,>and registers them scoped,MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:78) and then wrapped by a layered decorator pipeline. The verified registration inMMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:167-178lists the command pipeline outermost first, andDecorateInExecutionOrderapplies that list innermost first because each decoration wraps the registration as it stands (DependencyInjection.cs:403-409). The execution order is ViewAsCommandDecorator<TCommand, TResult>, FeatureGateCommandDecorator<TCommand, TResult>, AuthorizationCommandDecorator<TCommand, TResult>, LoggingCommandDecorator<TCommand, TResult>, CachingCommandDecorator<TCommand, TResult> (present only when the host opted in throughAddQueryCaching(),DependencyInjection.cs:162-165and:174), ValidatingCommandDecorator<TCommand, TResult>, TimeoutCommandDecorator<TCommand, TResult>, TransactionalCommandDecorator<TCommand, TResult>, then the concrete handler. That is exactly the nesting diagram in the method's own doc comment (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:90-101). The ordering is load-bearing and is the subject of ADR-014 (the CQRS decorator pipeline), whose 2026-08-18 revision inserted Authorization and Timeout into both chains. The defaultCancellationToken = default(line 17) lets token-less callers invoke handlers while still letting every implementation honour cancellation. - Walkthrough: line 9 declares
public interface ICommandHandler<in TCommand, TResult>. Theinvariance onTCommandis contravariant: a handler accepting a base command can stand in where a handler of a derived command is expected. Line 17 declares the sole member,Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken = default);. - Why it's built this way: a thin one-method interface keeps handlers focused; the decorator pipeline adds cross-cutting concerns without each handler knowing about them. A single open-generic interface is exactly what lets Scrutor register every closed handler in one assembly pass and lets the decorator chain wrap them generically. The registration-order constraint is documented on the method itself (
MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:81-83) and inMMCA.Common/AGENTS.md:AddApplicationDecorators()runs last, because decoration can only wrap handlers already in the container, and the framework now enforces that by sealing the pipeline after the decorators are registered (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:191). - Where it's used: every command handler in ADC and Store implements it, plus the framework's own generic write handlers (DeleteEntityHandler<TEntity, TIdentifierType>, CreateEntityHandler<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>, UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>), which
AddEntityCrudregisters as closed handlers withTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:82-92), and the notification command handlers (G10). - Caveats / not-in-source:
ProfilingCommandDecoratorexists but is not in the standard pipeline; it is added only by the separate opt-inAddApplicationProfiling()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:237-243).
ICommandWithRequest<out TRequest>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Contracts·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommandWithRequest.cs:14· Level 0 · interface
- What it is: a contract for commands that embed a request DTO as a
Requestproperty, enabling automatic FluentValidation of that DTO by the validating decorator before the handler runs. - Depends on: nothing first-party at the interface level. The validation plumbing resolves FluentValidation's
IValidator<TRequest>from DI through the framework-supplied CommandRequestValidator<TCommand, TRequest> and is enforced by ValidatingCommandDecorator<TCommand, TResult>. Cross-reference ICommandHandler<in TCommand, TResult>. - Concept introduced, automatic validator wiring via an interface contract.
[Rubric §24, Forms, Validation & UX Safety]assesses how server-side validation is centralised rather than scattered; instead of each handler calling_validator.ValidateAsync(command.Request), module scanning reflects over the assembly, finds every type closingICommandWithRequest<>, builds the closedCommandRequestValidator<TCommand, TRequest>and registers it asIValidator<TCommand>withTryAddsemantics (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:86-100).TryAddTransientat line 99 is what makes an explicitly writtenIValidator<TCommand>win:AddValidatorsFromAssemblyruns first (:82) and the auto-wired validator only fills the gap.[Rubric §1, SOLID](open for extension, closed for modification): a new command gets validation for free by implementing the interface, with no decorator or registration change. The same closed validator can also be registered explicitly throughAddCommandRequestValidator<TCommand, TRequest>(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:220-226), which is what the generic CRUD registration does for the update command (DependencyInjection.Crud.cs:94-96). - Walkthrough: line 14 declares
public interface ICommandWithRequest<out TRequest>. Theout(covariant) position means a command whose request is a derived type satisfies a constraint expecting the base request type. Line 17 declaresTRequest Request { get; }, the embedded payload, typically deserialized from the HTTP body. The XML doc on lines 5-11 is the contract for the auto-registration described above. - Why it's built this way: it collapses the usual web-API sequence (receive body, map to command, validate body, call handler) into "map to a command that implements
ICommandWithRequest, decorator validates, handler runs", removing per-handler validation boilerplate. - Where it's used: on the write commands whose payload is a request record rather than a flat set of positional parameters. Verified by source search, 11 implementers in
MMCA.ADC/Source(UpdateEventCommand.cs:14,UpdateQuestionCommand.cs:13,UpdateSessionCommand.cs:14,AddSessionAssetLinkCommand.cs:22,UpdateSessionAssetCommand.cs:18,ChangePasswordCommand.cs:13,ConfirmEmailCommand.cs:12,ForgotPasswordCommand.cs:21,ResetPasswordCommand.cs:11,SendEmailConfirmationCommand.cs:21,SendSignInLinkCommand.cs:21) and 16 inMMCA.Store/Source(ChangeVariantPriceCommand.cs:18,ChangeVariantSkuCommand.cs:18,ClearVariantDiscountCommand.cs:18,SetProductDiscountCommand.cs:18,SetVariantDiscountCommand.cs:18,ChangePasswordCommand.cs:13,ConfirmEmailCommand.cs:12,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/EmailConfirmation/SendEmailConfirmationCommand.cs:28,ForgotPasswordCommand.cs:21,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:13,ConfirmTwoFactorEnrollmentCommand.cs:14,DisableTwoFactorCommand.cs:14,RegenerateRecoveryCodesCommand.cs:14,BulkSetInventoryCommand.cs:22,AddItemCommand.cs:11). Commands that carry their parameters positionally simply do not implement it and pass the validating decorator unchanged.
IQuery<TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Contracts·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/IQuery.cs:26· Level 0 · interface (marker, empty)
- What it is: the read-side twin of ICommand<TResult>: an opt-in, member-less marker by which a query record declares the result type its handler produces.
- Depends on: nothing at runtime;
SuppressMessage(BCL) is applied to it. Read by CqrsContractInspector and paired against IQueryHandler<in TQuery, TResult>. - Concept reinforced, the phantom type parameter (taught under ICommand<TResult>).
[Rubric §6, CQRS & Event-Driven]assesses how cleanly the two sides are separated; having a separate marker per side is what makes aHandlerKindmismatch detectable at all: a request that declaresIQuery<T>but is handled by an ICommandHandler<in TCommand, TResult> has stated one thing and been implemented as another, and the inspector reports it as CqrsContractMismatchKind.HandlerKind. A single sharedIRequest<T>marker would make that class of bug invisible. - Walkthrough: line 26 is the whole declaration,
public interface IQuery<TResult>;. Lines 22-25 carry theS2326suppression with the same justification as the command marker, cross-referencing it explicitly. The doc comment states the two guarantees: additive, exactly likeICommand<TResult>(:12-16), and consumed by CqrsContractInspector so a fitness test can assert that no handler contradicts the result type its query declares (:17-20). - Why it's built this way: see ICommand<TResult>. The pair is deliberately symmetric so that a reader who has learned one has learned both, and so that the inspector's
Comparecan treat "matching marker" and "opposite marker" as a single parameterised test (CqrsContractInspector.cs:129-133). - Where it's used: read only by CqrsContractInspector (
CqrsContractInspector.cs:130). - Caveats / not-in-source: as with the command marker, no production query in MMCA.ADC, MMCA.Store or MMCA.Helpdesk implements
IQuery<TResult>today; the only implementers are the inspector's own test fixtures (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/UseCases/CqrsContractInspectorTests.cs:92).
IQueryHandler<in TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Contracts·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/IQueryHandler.cs:10· Level 0 · interface
- What it is: the CQRS query-handler contract:
HandleAsyncaccepts a read-only query and returns a result without mutating state. - Depends on: BCL only. Mirrors ICommandHandler<in TCommand, TResult> on the read side.
- Concept introduced, the lighter read pipeline.
[Rubric §6, CQRS & Event-Driven]: this is the query half of the segregation. The verified registration inMMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:180-189lists, outermost first,FeatureGate,Authorization,Logging,Caching(only when the host opted in throughAddQueryCaching(),:186),Validating,Timeout, so the execution order is FeatureGateQueryDecorator<TQuery, TResult>, AuthorizationQueryDecorator<TQuery, TResult>, LoggingQueryDecorator<TQuery, TResult>, CachingQueryDecorator<TQuery, TResult>, ValidatingQueryDecorator<TQuery, TResult>, TimeoutQueryDecorator<TQuery, TResult>, then the concrete handler (DependencyInjection.cs:104-112). The one decorator the read chain does not have is Transactional: queries do not mutate, so there is nothing to commit or roll back, and that single omission is the clearest expression of CQRS in this codebase. Two orderings differ from the write side and both are argued in the registration doc. Validation sits inside caching here (:127-131): a cached entry can only exist because the same query already passed validation when the entry was produced, so re-validating on a cache hit spends work to reach a conclusion already reached. And the budget is innermost (:134-137), so a cache hit is served without starting a budget at all. - Walkthrough: line 9 declares
public interface IQueryHandler<in TQuery, TResult>with the same contravariantinon the query type. Line 17 declaresTask<TResult> HandleAsync(TQuery query, CancellationToken cancellationToken = default);. - Why it's built this way: an identical shape to
ICommandHandler(for the same Scrutor-discoverability and open-generic decorator reasons), but a separate interface so DI can tell "this is a query" from "this is a command" and apply the correct, lighter decorator set. ADR-014 records the chain and its 2026-08-26 revision is what added the Validating decorator to the query side. - Where it's used: every read handler in ADC and Store, plus the framework's notification query handlers (G10). Closed implementations are registered scoped by
ScanModuleApplicationServices(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:80). - Caveats / not-in-source: like the command side,
ProfilingQueryDecoratoris added only by the opt-inAddApplicationProfiling()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:237-243), not by the standard pipeline.
MutationContext
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutationContext.cs:31· Level 0 · class (sealed)
- What it is: the per-command side channel of a mutate handler's load-mutate-save workflow. It is two things at once: a typed key/value bag for values a mutation derived while the aggregate was loaded, and the
SkipSaveshort-circuit that stops the write without failing the command. - Depends on: BCL only (
Dictionary<string, object?>,MaybeNullWhen). Created and threaded by MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType> and read by MutateEntityPayloadHandlerBase<TCommand, TEntity, TIdentifierType, TResultPayload> and IEntityUpdateCommandApplier<TEntity, TUpdateRequest, TIdentifierType, in TCommand>. - Concept introduced, a request-scoped side channel instead of handler instance state. The workflow answers with the mutated aggregate, so anything the mutation computed on the way (the pre-mutation state, the blob name about to be orphaned, a warning the caller must be told about) has nowhere to go. Storing it in a field on the handler is the tempting move and the wrong one: handlers are registered scoped, and a field would leak between calls the moment a handler instance is reused. One context instance per command, handed to every hook in order and then to the result builder, makes the value travel with the command and die with it (
MutationContext.cs:11-18).[Rubric §1, SOLID]: the hooks stay single-purpose because none of them has to widen its signature to pass a value to the next one.[Rubric §14, Testability]: the context is a plain object with no framework dependency, so a hook that reads it can be tested by constructing one and callingSet.[Rubric §15, Best Practices & Code Quality]: keys are ordinary strings compared ordinally, which is why every consumer declares its ownprivate const stringkey beside the handler that uses it rather than passing a literal twice. Not thread-safe by design (:26-29): one command runs on one logical flow, and a hook that fans out must collect its own results before writing them here. - Walkthrough: line 31 declares
public sealed class MutationContext; line 33 holds the backingDictionary<string, object?> _items = []. Line 39 exposesSaveSkipped { get; private set; }, the read side of the short-circuit, and line 42 exposesItemsas anIReadOnlyDictionaryfor a hook that wants to inspect the whole bag. Line 49 is the short-circuit itself,public void SkipSave() => SaveSkipped = true, documented as idempotent (calling it twice is harmless). The bag has three accessors:Set<TValue>(string key, TValue value)(:56-61) writes, replacing any value under the same key;TryGet<TValue>(:69-81) reads with a type test,_items.TryGetValue(key, out var stored) && stored is TValue typed, so a key holding another type reads as absent rather than throwing; andGetOrDefault<TValue>(:93) is the one-line convenience overTryGetfor when "absent" and "default" need not be told apart.Contains(:99-104) tests presence whatever the value's type. All four throwArgumentNullExceptionon a null key. - Why it's built this way: ADR-099 records it, in the 2026-08-30 revision that closed the shapes still forcing a hand-written handler. The
SkipSavehalf is the more subtle contribution. It marks the command as already satisfied, which is a success, not a refused invariant: the workflow returns the loaded aggregate successfully, issues no save, and runs neitherLogMutatednorOnMutatedAsync(MutationContext.cs:20-24, enforced atMMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutateEntityHandlerBase.cs:318-319). Without it, the idempotent no-op (remove an avatar that is not there, close an already-closed record) had only two bad options: fail a command that did nothing wrong, or save nothing while logging a mutation that never happened. - Where it's used: created once per run by
CreateContext()(MutateEntityHandlerBase.cs:98, overridable) and threaded throughMutateCoreAsync(:270-308) intoLoadAsync(:280),MutateAsync(:293),LogMutated(:304) andOnMutatedAsync(:305), plusBuildResulton the payload-returning base (:418). In the framework it also reaches UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest> (UpdateEntityHandler.cs:221) and the applier contract (IEntityUpdateCommandApplier.cs:59). Six ADC handlers use it in production: RemoveUserAvatarHandler is the clearest worked example, declaringprivate const string BlobNameKey = "Avatar.BlobName"(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RemoveUserAvatar/RemoveUserAvatarHandler.cs:25), callingcontext.SkipSave()when there is no avatar to remove (:39), writing the blob name withcontext.Setbefore clearing the URL (:43), and reading it back withcontext.GetOrDefault<string>in the post-commit hook that deletes the blob (:65). The others are SetUserAvatarHandler, UpdateSessionHandler,UpdateEventHandler,AddRoomHandlerandSpeakerUpdateApplier. - Caveats / not-in-source: a type-mismatched read is indistinguishable from an absent key, by design (
MutationContext.cs:73), so a writer and a reader that disagree onTValuefail quietly rather than loudly. Nothing in the type validates key spelling either; theprivate const stringconvention is what keeps a writer and reader in agreement, and it is a convention, not an enforced rule.
DeleteEntityCommand<TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/DeleteEntityCommand.cs:13· Level 2 · record (sealed)
- What it is: a generic delete command carrying the entity's primary key
Idplus a cache prefix to evict. TheTEntitytype parameter does double duty: it discriminates handlers in DI, and it supplies the defaultCachePrefix. - Depends on: ICacheInvalidating (implemented, line 13) and EntityCachePrefix for the default prefix (
DeleteEntityCommand.cs:22;EntityCachePrefix.For<TEntity>()answerstypeof(TEntity).FullName + ":",MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/EntityCachePrefix.cs:14,:19-24). Participates in the pipeline described under ICommandHandler<in TCommand, TResult>; handled generically by DeleteEntityHandler<TEntity, TIdentifierType>. - Concept introduced, a type parameter as both a dispatch key and a data source.
[Rubric §1, SOLID]assesses single responsibility and extension without modification; one closed handler per entity type keeps dispatch unambiguous.[Rubric §6, CQRS & Event-Driven]assesses the write/read segregation; this is a pure write command. WithoutTEntity, every delete command sharing aTIdentifierType(sayint) would collapse onto one closed generic and handler registration would be ambiguous. The second use is the more interesting one: because the generic controller constructs this command itself, no caller is in a position to pass a cache prefix, so the command computes the conventional one. - Walkthrough: line 13 declares
public sealed record DeleteEntityCommand<TEntity, TIdentifierType>(TIdentifierType Id) : ICacheInvalidating; the record primary constructor makesIda positionalinitproperty, andsealedprevents inheritance. Line 14 constrainswhere TIdentifierType : notnull, forbidding a nullable key type. Line 22 implements the interface member:public string CachePrefix { get; init; } = EntityCachePrefix.For<TEntity>();, the one helper that builds the{entity full name}:prefix so the delete command, the update command and every other framework caller compute it identically. Two things follow from that one line. It isinit, so a caller that wants a narrower prefix can set one at construction. And its default is the aggregate-prefix convention every consumer already keys its cached reads under, which is exactly the prefix ADC's cached GetNowNextQuery sits behind (see IQueryCacheable). Setting it to an empty string is the documented opt-out (lines 16-21), and it works because the caching decorator refuses a blank prefix rather than evicting the whole cache. - Why it's built this way: it avoids hand-writing a bespoke
DeleteSessionCommand,DeleteSpeakerCommandand so on in every module; one generic command plus one generic handler covers the boilerplate while the type system still routes each call to the correct closed handler. ADR-099 records the generic write-side family this belongs to. Defaulting the prefix rather than leaving it blank means the generic delete path invalidates caches by default, which is the safe direction for a mutation whose call site cannot make the decision. - Where it's used: the aggregate-root and CRUD controller delete actions construct it directly: AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest> injects
ICommandHandler<DeleteEntityCommand<TEntity, TIdentifierType>, Result>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AggregateRootEntityControllerBase.cs:36) and calls it with a fresh command at:93, and CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> takes the same dependency (CrudEntityControllerBase.cs:64). The default handler for it is registered byAddEntityCrudwithTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:90-92), so a module that wants a cascade registers its own override first and wins.
UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/UpdateEntityCommand.cs:48· Level 5 · record
- What it is: the generic update command for any aggregate root: the entity's primary key, the update request the aggregate has to accept, and the caller's last-observed concurrency token. It is the write-side twin of DeleteEntityCommand<TEntity, TIdentifierType>, and unlike that record it is deliberately not sealed.
- Depends on: ICommandWithRequest<out TRequest> and ICacheInvalidating, both implemented at
UpdateEntityCommand.cs:52; EntityCachePrefix for the default prefix (EntityCachePrefix.For<TEntity>(),:65). Served by UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>, and by UpdateEntityCommandHandler<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest> when a module derives from it. - Concept introduced, a framework command designed to be inherited.
[Rubric §9, API & Contract Design]assesses whether a shared contract can absorb a caller's extra requirements without either forking or being widened for everyone;[Rubric §1, SOLID]assesses extension without modification. The problem this record solves is that a real update usually carries state the request body must not carry: an id taken from the route rather than the body, a flag the server decided rather than the caller, a second concurrency token for a child row (UpdateEntityCommand.cs:28-37). Flattening those into the request DTO would let a caller set them. The answer is that a module declares a positional record deriving from this one, inheritingId,Request,RowVersion, the validator bridge and the cache prefix, and adds its own properties beside them. ADC'sUpdateSpeakerCommandis exactly that shape: it addsCallerIsOrganizer, bound at the API edge and never from the body (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/UseCases/Update/UpdateSpeakerCommand.cs:25-31).[Rubric §6, CQRS & Event-Driven]: the mutation itself is nowhere in this file. It lives on the aggregate, reached through the module's applier, which is what keeps one generic command usable for every entity without the command knowing a single field name (:20-24). - Walkthrough
- The declaration (
UpdateEntityCommand.cs:48-53):public record UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType>(TIdentifierType Id, TUpdateRequest Request, byte[] RowVersion), implementing both marker interfaces and constrainedwhere TIdentifierType : notnull. The three positional parameters becomeinitproperties, and the missingsealedis the design decision described above. Requestand the validator bridge: because the command carries the request rather than flattening it, implementing ICommandWithRequest<out TRequest> is enough for the framework to register aCommandRequestValidatorclosed over it, so a module writes onlyIValidator<TUpdateRequest>and the command is validated before the transaction opens (:13-19).AddEntityCrudregisters that bridge for the closed command itself, because a generic built at registration time cannot be seen by the module scan's reflection bridge (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:94-96, rationale at:54-62).RowVersion(:42-45): the caller's last-observed token, taken from the request'sIf-Matchheader, and required, because a conditional write with no precondition never reaches a handler (ADR-035).CachePrefix(:65):public string CachePrefix { get; init; } = EntityCachePrefix.For<TEntity>();, the same{entity full name}:prefix the delete command computes through the same helper. Same reasoning as the delete command: the generic controller constructs the command, so no caller is in a position to supply a prefix, and the default is the aggregate-prefix convention every consumer already keys its cached reads under. An empty string is the documented opt-out, and a derived command inherits both the default and the opt-out and can narrow it per verb (:55-64).- The verb-discriminated sibling (
:102-116):UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType, TApplier>derives from this record and adds a fourth, purely phantom type parameter. It exists because the three-parameter command keys on (entity, request, identifier), so an aggregate with two verbs over one request shape (an inventory item increased or decreased by the sameQuantitypayload) cannot close it twice: both verbs would resolve the same handler and the same applier (:72-81).TApplierdiscriminates them, constrained to anIEntityUpdateApplierimplementation (:109), and theApplierTypeproperty (:116) surfaces the discriminator in a log line or a test assertion instead of only in the type name. The wire shape does not change: route and request DTO stay what they were (:82-87).
- The declaration (
- Why it's built this way: ADR-099 records the whole generic write side and states the constraint that shaped this record: the mutation cannot move into the framework, because an update names fields and a framework type that names fields is a framework type per aggregate; worse, writing properties directly would route around the aggregate's guarded methods, where the invariants and the domain events live.
- Where it's used: CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> injects
ICommandHandler<UpdateEntityCommand<...>, Result<TEntityDTO>>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/CrudEntityControllerBase.cs:63, exposed at:77) and constructs a fresh command in its PUT action (:105).AddEntityCrudregisters the default handler withTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:86-88); Helpdesk's Tickets module calls it (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/DependencyInjection.cs:54), and Store's Identity module calls it three times, once per update request shape (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:65-67). Store's Sales module registers the verb-discriminated sibling twice for inventory (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/DependencyInjection.cs:78-79).
IEntityUpdateCommandApplier<TEntity, TUpdateRequest, TIdentifierType, in TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/IEntityUpdateCommandApplier.cs:38· Level 6 · interface
- What it is: the command-aware twin of IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>. It applies an incoming update command to an already-loaded aggregate, receiving the whole command rather than only its request, so an update that depends on state the request does not carry can still run on the generic path.
- Depends on: UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> (the
TCommandconstraint,IEntityUpdateCommandApplier.cs:41); AuditableBaseEntity<TIdentifierType> (:39); MutationContext and Result (:56-60). - Concept introduced, contravariance plus a constraint used as an extension point.
[Rubric §1, SOLID]assesses interface segregation and dependency inversion: the framework depends on this one-method abstraction and the module supplies the field-naming half.[Rubric §4, DDD]assesses whether mutation stays behind the aggregate's guarded methods; the interface returns a bareResultprecisely because the instance handed in is the tracked one, so a successful apply has already mutated it in place and a failure must leave it untouched (:28-32). The load-bearing detail is theTCommandconstraint at:41: it is what gives an implementation the inheritedId,RequestandRowVersionalongside its own properties, and theinmodifier makes the parameter contravariant, so an implementation written against a derived command is usable wherever the framework asks for that exact closed interface. The interface lives beside the command rather than with the request-only applier for the same reason (:22-27). - Walkthrough: line 38 declares the interface with four type parameters, the fourth contravariant. Constraints at
:39-41pinTEntityto an auditable entity,TIdentifierTypetonotnull, andTCommandto a subclass of the generic update command. The single member,ApplyAsync(TEntity entity, TCommand command, MutationContext context, CancellationToken cancellationToken = default)(:56-60), returnsTask<Result>. The third parameter is the run's MutationContext: write a derived value the handler's post-save hooks or its result need, or callSkipSave()to finish an already-satisfied command without writing (:49-53). Implementations are auto-registered by Scrutor assembly scanning, exactly like the request-only applier (:10-11). - Why it's built this way: a request DTO is the body a caller sent, and plenty of updates depend on more than the body (
:14-21). Those extra values belong on the command, not smuggled into the request DTO where a caller could set them, so the applier has to see the command. It is one of the five surface extensions the 2026-08-30 revision of ADR-099 added to close the shapes that still forced a hand-written handler. - Where it's used: resolved and called by UpdateEntityCommandHandler<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest> (
MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/UpdateEntityHandler.cs:187, invoked at:223), whichAddEntityUpdateregisters (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:195-197). ADC'sSpeakerUpdateApplieris the production implementation: it takes the command-aware form because BR-214 turns onCallerCanManageSpeakersand BR-66 onCallerCanSeeEmail, which the server decides at the API edge and the request body must never carry (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/UseCases/Update/SpeakerUpdateApplier.cs:10-13), and it uses the first flag to keep the entity's storedIsTopSpeakeron a self-edit (:36) before delegating toSpeaker.Update(:50). ADC's registration test asserts the applier is registered under this exact closed interface (MMCA.ADC/Tests/Modules/Conference/MMCA.ADC.Conference.Application.Tests/ConferenceCrudRegistrationTests.cs:124).
AddChildEntityHandlerBase<TCommand, TParent, TIdentifierType, TChild, TChildDTO>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/ChildEntityHandlerBase.cs:43· Level 8 · class (abstract)
- What it is: the shared "add a child to an aggregate" workflow: load the parent tracked and with its child collection included, fail with
NotFoundwhen it is gone, delegate to the aggregate method that owns the invariant, save only on success, and answer with the new child's DTO. - Depends on: IUnitOfWork (primary-constructor injected,
ChildEntityHandlerBase.cs:44); ICommandHandler<in TCommand, TResult> (implemented at:45); AuditableAggregateRootEntity<TIdentifierType> (theTParentconstraint,:46); IUniqueConstraintViolationDetector (tested against the unit of work in the save catch,:139-140); Result and Error (:128,:132,:156). - Concept introduced, an abstract member used to force a decision rather than to allow one.
[Rubric §2, Design Patterns]assesses the template-method shape: the base owns the sequence and the subclass supplies the steps.[Rubric §8, Data Architecture]assesses how a write behaves against the store, and this base is the clearest example in the framework of an eager-load choice being a correctness question rather than a performance one.Includesis abstract (:68) even though an empty list is a legal answer, because loading the child collection is what makes the aggregate's duplicate check meaningful; the comment inHandleAsyncsays what happens otherwise, the check runs against an empty in-memory list and a double-submit surfaces as a raw unique-index 409 (:123-124). Naming the collection therefore has to be a deliberate act, and an add whose aggregate genuinely reads no existing child returns[]and says so (:15-18), which is what ADC'sAddCategoryItemHandlerdoes with an explanatory comment (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Categories/UseCases/AddCategoryItem/AddCategoryItemHandler.cs:21-23). - Walkthrough
- Declaration (
ChildEntityHandlerBase.cs:43-47): five type parameters,ICommandHandler<TCommand, Result<TChildDTO>>as the implemented interface, and constraints pinningTParentto an auditable aggregate root andTIdentifierTypetonotnull. Note there is no constraint onTChildorTChildDTO. UnitOfWork(:50): the injected unit of work re-exposed as a protected property, so an override can reach another repository.HandlerName(:56): defaults toGetType().Name, the concrete handler's own name, which is what every hand-written copy passed.AsTracking(:62):trueby default, because a no-tracking load would turn the add into a silent no-op.Includes(:68),ParentId(:73),Apply(:82) andMapChild(:87): the four abstract members.ApplyreturnsResult<TChild>and is where the aggregate method that owns the invariant (uniqueness, capacity, state) is called; a failure short-circuits before the save.LogAdded(:96-99) andOnAddedAsync(:115-116): the two virtual post-commit hooks, both no-ops by default. The logging hook is empty on purpose, with the comment stating the reason: logging is per-module vocabulary, so the base provides only the call site (:98).OnAddedAsyncruns after the save has committed and is not guarded: its doc says an override that does I/O must catch and log its own failures, because an exception there reports an already-committed write as failed and the client's retry re-runs a write that landed (:104-108).HandleAsync(:119-163): resolve the repository from the unit of work (:121), load withGetByIdAsync(ParentId(command), Includes, AsTracking, ...)(:125-127), returnError.NotFound.For<TParent>(HandlerName)when the parent is missing (:128-129), which stampsSourcewith the handler name andTargetwithtypeof(TParent).Namein one call (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:163-164), runApplyand unwrap it withresult.TryGetValue(out var child), returning its errors unchanged on refusal (:131-133), so the new child is bound once, before the save, with no laterValue!read; then save inside atry(:135-138), then log, run the async hook, and answer withResult.Success(MapChild(child))(:159-162).- The lost-insert-race catch (
:139-157): thecatchfilter fires only when the unit of work is anIUniqueConstraintViolationDetectorthat classifies the exception as a unique-constraint violation (:139-140). The tracked parent already holds this request's own pending child, so the handler re-reads the parent untracked (asTracking: false,:146-148) and re-runsApplyon that stored copy (:152). If the stored parent is gone (:149-150) or the re-run succeeds (:153-154), the original exception is rethrown unchanged, so a key collision or another index still propagates. Only when the re-run refuses, meaning a concurrent request really did save the same child, does the handler return the aggregate's own duplicate errors (:156), the same answer a sequential second add gets in place of the generic data-conflict 409. The class remarks state this contract (:26-35). MapChildrather than an injected mapper (:21-23): the DTO belongs to the child entity, whose identifier type is usually not the parent's, so an injectedIEntityDTOMapperclosed over the parent's types would be the wrong mapper. Implementations are one-liners into the module's own child mapper (AddCategoryItemHandler.cs:34).
- Declaration (
- Why it's built this way: the add-a-child slice is the same nine lines in every module, and the parts that genuinely differ (which id addresses the parent, which aggregate method to call, which mapper) are exactly the four abstract members. ADR-099 covers the generic write-side family this belongs to.
- Where it's used: ADC subclasses it across Conference for every child-collection add:
AddCategoryItemHandler(AddCategoryItemHandler.cs:19),AddEventSpeakerHandler(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/AddEventSpeaker/AddEventSpeakerHandler.cs:24),AddSpeakerCategoryItemHandler(.../Speakers/UseCases/AddSpeakerCategoryItem/AddSpeakerCategoryItemHandler.cs:20),AddSessionCategoryItemHandler(.../Sessions/UseCases/AddSessionCategoryItem/AddSessionCategoryItemHandler.cs:21) andAddSessionSpeakerHandler(.../Sessions/UseCases/AddSessionSpeaker/AddSessionSpeakerHandler.cs:21). Exercised by ChildEntityHandlerBaseTests.
CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/CreateEntityHandlerBase.cs:42· Level 8 · class (abstract)
- What it is: the shared create-an-aggregate workflow: map the request through the entity's factory, add the new aggregate to its repository, save, and return the mapped DTO. A module's create handler subclasses it and adds only what is genuinely its own.
- Depends on: IUnitOfWork, IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType> and IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>, all three primary-constructor injected (
CreateEntityHandlerBase.cs:43-45); ICommandHandler<in TCommand, TResult> (:46); ICreateRequest, AuditableAggregateRootEntity<TIdentifierType> and IBaseDTO<TIdentifierType> as constraints (:47-50); IRepository<TEntity, TIdentifierType> as a hook parameter (:128). - Concept introduced, attempt scope: passing the unit of work as a parameter rather than only using the injected one.
[Rubric §2, Design Patterns]for the template method;[Rubric §8, Data Architecture]for the retry story. A create path that computes its own primary key can lose a race and hit a unique-constraint collision, and a naive retry against the injected unit of work never persists, because the ambient DbContext still tracks the failed insert.CreateCoreAsynctherefore takes the unit of work as a parameter (:77-80), so a subclass can overrideHandleAsync, wrap the workflow in a retry loop, and run each attempt against a fresh DI scope's unit of work while reusing the whole workflow (:28-35). The same attempt-scope shape appears on the mutate side in MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType>.[Rubric §3, Clean Architecture]: the repository is obtained from IUnitOfWork inside the workflow rather than constructor-injected, because only the unit of work knows which physical data source the entity resolves to (:23-27). - Walkthrough
- Declaration (
CreateEntityHandlerBase.cs:42-51): an abstract class that implements the handler interface. The class doc states why that is the shape (:16-22): the concrete app subclass stays the registered handler, soScanModuleApplicationServiceskeeps discovering it and the decorator pipeline keeps wrapping it, and Scrutor never registers the abstract base itself. Note also thatTCreateRequestis the command: there is no separate create command type. UnitOfWork(:53): protected re-exposure of the injected instance.HandleAsync(:56-63): null-guards the command and returnsCreateCoreAsync(unitOfWork, ...)directly, a non-asyncmethod that hands back the inner task without an extra state machine (:62). It isvirtual, which is the hook a retrying subclass overrides.CreateCoreAsync(:77-100): the workflow proper. Null-guard (:82),PrepareAsyncunwrapped withprepared.TryGetValue(out var request)and an early return of its errors on failure (:84-86), map throughrequestMapper.CreateEntityAsyncand unwrap withresult.TryGetValue(out var entity), returning its errors unchanged (:88-90), resolve the repository from the attempt unit of work (:92),PersistAsync(:94), thenLogCreated,OnCreatedAsyncandResult.Success(dtoMapper.MapToDTO(entity))(:96-99). Each step's value is bound by the same test that checks for failure, so there is no separateValue!read.PrepareAsync(:111-115): pass-through by default (Task.FromResult(Result.Success(command))). Override to resolve an app-assigned primary key or to run a cross-aggregate validation whose failure must stop the create; a retrying subclass overrides it to recompute the id per attempt.PersistAsync(:126-137):repository.AddAsyncthenattemptUnitOfWork.SaveChangesAsync, which is what every create path does today; it exists as a hook for a create that needs a different persist step.LogCreated(:145-148) andOnCreatedAsync(:169-170): the two post-save hooks.OnCreatedAsyncruns after the save, which is what makes it the right place to publish an integration event carrying the now-known database-generated id (:151-153). Whether "after the save" also means "after the commit" depends on the command (:155-160). For a create request that is not ITransactional, the save is the commit, so an exception in the hook reports an already-committed write as failed and the client's retry re-runs a write that landed. For anITransactionalone, TransactionalCommandDecorator<TCommand, TResult> commits only after the handler returns, so the hook runs before the commit: an exception rolls the write back, and any side effect the hook already performed stands for a write that never committed, which is why such work belongs past the commit (an internal command or an integration event). Either way the hook runs unguarded: the base has no logger, so an override that does I/O must catch and log its own failures (:161-162), and the caching decorator still evicts the command's cache prefix when the handler throws (:162-163).
- Declaration (
- Why it's built this way: ADR-099 targets the module scaffolded from the template, where the create handler is the same handful of lines every time; the base keeps the sequence and leaves the module its
[LoggerMessage]partial, its pre-map validation and its post-save publish. - Where it's used: ADC's Conference module subclasses it for every aggregate create:
CreateEventHandler(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/Create/CreateEventHandler.cs:22),CreateSpeakerHandler(.../Speakers/UseCases/Create/CreateSpeakerHandler.cs:20),CreateSponsorHandler(.../Sponsors/UseCases/Create/CreateSponsorHandler.cs:22),CreatePartnerHandler(.../Partners/UseCases/Create/CreatePartnerHandler.cs:22),CreateSessionHandler(.../Sessions/UseCases/Create/CreateSessionHandler.cs:29),CreateActivityHandler(.../Activities/UseCases/Create/CreateActivityHandler.cs:22),CreateConferenceCategoryHandler(.../Categories/UseCases/Create/CreateConferenceCategoryHandler.cs:20) andCreateQuestionHandler(.../Questions/UseCases/Create/CreateQuestionHandler.cs:25). Its zero-override closure is CreateEntityHandler<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>. Exercised by CreateEntityHandlerBaseTests.
DeleteEntityHandler<TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/DeleteEntityHandler.cs:36· Level 8 · class
- What it is: the generic delete handler that works for any aggregate root, implementing
ICommandHandler<DeleteEntityCommand<TEntity, TIdentifierType>, Result>(DeleteEntityHandler.cs:38). It loads the aggregate, gives a subclass one chance to refuse, calls the aggregate's ownDelete(), and saves only when that succeeded. - Depends on: IUnitOfWork (primary-constructor injected,
:36); DeleteEntityCommand<TEntity, TIdentifierType> (the command it handles); ICommandHandler<in TCommand, TResult>; AuditableAggregateRootEntity<TIdentifierType> (constraint,:38); IRepository<TEntity, TIdentifierType> (:101); Result and Error. - Concept reinforced, one handler for every aggregate, left open for the two things a delete outgrows.
[Rubric §1, SOLID]and[Rubric §6, CQRS & Event-Driven]. The class is not sealed, and the doc names the two structural reasons a real delete needs more (:12-21): the child collections the aggregate's ownDelete()cascade has to see, declared inIncludes, and a cross-aggregate invariant that must refuse the delete before it happens, implemented inOnDeletingAsync. A subclass that overrides neither behaves exactly like this handler, down to the query it issues.[Rubric §4, DDD]: no events are raised here (:22-25); domain events belong to the aggregate'sDelete(), which is what keeps the generic path and a hand-written one indistinguishable from the outside.[Rubric §34, Architecture Governance & Documentation]: the framework's own naming fitness rules (handlers end inHandlerand are sealed) and the vertical-slice co-location rule are scoped to a repo's module assemblies, so this deliberately unsealed framework generic sits outside them while a consumer's subclass is a normal module handler and must be sealed and co-located (:26-31). - Walkthrough
HandlerName(:49):nameof(DeleteEntityHandler<,>), the open handler name rather than the runtime backtick-2 suffixed one, so the failure reads the same whichever subclass produced it.Includes(:57): empty by default, which issues the same by-id query the handler has always issued. The doc states the failure mode of not overriding it: an unloaded collection leaves its rows live under a soft-deleted parent (:51-56).AsTracking(:63):true, because a no-tracking load would turn the delete into a silent no-op.HandleAsync(:66-88): resolve the repository (:70),LoadAsync(:71),Error.NotFound.For<TEntity>(HandlerName)when null (:72-73; the sameSourceandTargetthe chainedWithSource/WithTargetpair produced,MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:163-164),OnDeletingAsyncand an early return on refusal (:75-77), thenentity.Delete()(:79) with the save and the log guarded byresult.IsSuccess(:80-85), returning the entity's own result either way (:87).LoadAsync(:100-113): materializesIncludesonce into a read-only collection (:108) and then branches, calling the bareGetByIdAsync(command.Id, ...)when there is nothing to include and the eager-loading overload underAsTrackingwhen there is (:110-112). That branch is why an un-overridden subclass issues a byte-identical query to the base.OnDeletingAsync(:125-129): returns success by default. It is the hook for an invariant the aggregate itself cannot check because it spans more than the aggregate; a failure returns to the caller unchanged and nothing is saved.LogDeleted(:137-140): the usual no-op logging call site.
- Why it's built this way: most deletes are identical (load,
Delete(), save), so the framework supplies the handler once on top of Common's soft-delete convention (ADR-005), and a module overrides only where its aggregate genuinely differs. Returning the entity's ownDelete()result lets a domain-level refusal propagate as a value rather than an exception. The extensible shape (theIncludes,AsTracking,LoadAsyncandOnDeletingAsynchooks) is one of the five extensions in the 2026-08-30 revision of ADR-099. - Where it's used: registered as the delete slot by
AddEntityCrudwithTryAddScoped, so a module that registers its own subclass first wins (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:90-92,:44-52). Subclassed where an aggregate cascades: ADC'sDeleteSessionHandlerdeclares the three owned join collections BR-55 soft-deletes, because the cascade only reaches children actually loaded (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/Delete/DeleteSessionHandler.cs:31,:25-26), ADC'sDeleteConferenceCategoryHandlerandDeleteLivePollHandlerdo the same shape (.../Categories/UseCases/Delete/DeleteConferenceCategoryHandler.cs:15,MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/LivePolls/UseCases/Delete/DeleteLivePollHandler.cs:15), and Store'sDeleteCategoryHandlerincludesProductsand the inverse self-reference so the aggregate's two refusals can see their rows (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Categories/UseCases/Delete/DeleteCategoryHandler.cs:33,:39-40). Exercised by DeleteEntityHandlerTests. - Caveats / not-in-source: the command it handles does not implement ITransactional, so a delete that raises domain events relies on
SaveChangesAsyncwriting the data plus its outbox rows in one transaction rather than on a handler-level transaction; the outbox is the durability mechanism (ADR-003). Cache invalidation is free, because the command implements ICacheInvalidating with a defaulted prefix.
MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutateEntityHandlerBase.cs:52· Level 8 · class (abstract)
- What it is: the shared load-mutate-save machinery behind every aggregate write handler: resolve the repository, load the aggregate tracked and with the includes the mutation needs, fail with
NotFoundwhen it is gone, stamp the caller's optimistic-concurrency token, run the domain mutation, and save only when the mutation succeeded. It is the single most reused type on the write side of this codebase. - Depends on: IUnitOfWork (primary-constructor injected,
MutateEntityHandlerBase.cs:52); AuditableAggregateRootEntity<TIdentifierType> (constraint,:53); IRepository<TEntity, TIdentifierType> (:153,:173,:294); MutationContext (:98,:139,:288); Result and Error. - Concept introduced, a base class that deliberately implements no handler interface.
[Rubric §1, SOLID]and[Rubric §6, CQRS & Event-Driven]. This type does not implement ICommandHandler<in TCommand, TResult>, and the reason is registration mechanics (:18-27): the three shapes a real handler returns (a bareResultfor verb-style commands, aResult<T>carrying the refreshed DTO, and aResult<T>carrying a payload the handler builds) are supplied by three thin subclasses, and keeping the machinery in a fourth, interface-free type means a single handler type never advertises two handler interfaces, which would otherwise register a bogus second handler entry during the module scan.[Rubric §8, Data Architecture]: the concurrency stamp at:305-310is the ADR-035 mechanism made generic, and the block comment above it spells out the alternative it prevents, silent last-write-wins (:299-304). A second stamp-adjacent fix,repository.TouchConcurrencyToken(entity)at:327-328, closes SEC-Common-77: stamping the original token alone does not dirty the root, so an applier that touched only child rows left the rootUnchanged, EF emitted no rootUPDATE, and a staleIf-Matchwas never evaluated; touching the root on every conditional write (:327) guarantees the root always emits anUPDATEcarrying the caller's token, so a stale one now answers 412 as ADR-035 states (comment at:321-326).[Rubric §29, Resilience, Reliability & Business Continuity]: the MutationContext is how a value derived while the aggregate was loaded reaches the post-save hooks and the handler's own result without handler instance state (:34-38). - Walkthrough
- Declaration (
:52-54):public abstract class MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType>(IUnitOfWork unitOfWork), with no base type and no interface.TCommandis unconstrained. UnitOfWork(:57),HandlerName(:63, defaults toGetType().Name),Includes(:70, empty),AsTracking(:76,true): the same four knobs the delete handler exposes.EntityId(:81): the one abstract member, extracting the aggregate's primary key from the command.RowVersion(:91): returnsnullby default, for a mutation whose endpoint states no precondition; a command reached through a conditional (If-Match) endpoint overrides it, where the token is always present.CreateContext(:98):new()by default; override only to pre-seed values every hook expects.- The paired overloads.
MutateAsync(:119-121and:136-141),LoadAsync(:152-160and:172-177),LogMutated(:187-190and:200-201) andOnMutatedAsync(:224-225and:241-246) each exist twice, once context-free and once context-aware, with the context-aware overload forwarding to the context-free one by default. The workflow always calls the context-aware member, so a handler that needs no context keeps overriding the simple overloads and never sees aMutationContext. The exception isMutateAsync, whose context-free overload throwsInvalidOperationExceptionnaming the offending type (:119-121): overriding exactly one of the two is required, and overriding neither is a programming error caught at first execution rather than silently doing nothing. - The post-save hook is unguarded, and whether it runs before or after the commit depends on the command. Both
OnMutatedAsyncdocs call it a post-save hook (:204,:228). For a command that is not ITransactional the save is the commit, so an exception in the hook reports an already-committed write as failed and the client's retry re-runs a write that landed (:209-211). For anITransactionalcommand TransactionalCommandDecorator<TCommand, TResult> commits only after the handler returns, so the hook runs before the commit: an exception rolls the write back, and any side effect the hook already performed (a blob delete, a broadcast) stands for a write that never committed, so such work should be deferred past the commit through an internal command or an integration event (:211-215, restated for the context-aware overload at:231-234). Either way the base has no logger and does not wrap the call, so an override that does I/O must catch and log its own failures, and the caching decorator still evicts the command's cache prefix when the handler throws (:215-217). The summary describes the hook as "follow-up work" such as enqueuing a broadcast or deleting the orphaned blob (:205-207), not as best-effort work that must never fail the command, because the base does not enforce that. MutateCoreAsync, three overloads (:255-256,:269-273,:285-336). The first two are conveniences that create a context and forward; the third is the workflow. It null-guards (:291-292), resolves the repository from the attempt unit of work (:294), loads through the context-awareLoadAsync(:295), returnsError.NotFound.For<TEntity>(HandlerName)when the aggregate is gone (:296-297;Sourceis the handler name,Targetistypeof(TEntity).Name,MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:163-164), stampsrepository.SetOriginalRowVersion(entity, rowVersion)and recordsconditionalWrite = truewhen the handler reported a non-empty token (:305-310), runs the mutation and returns its errors unchanged on refusal (:312-314), short-circuits oncontext.SaveSkippedby returning success without saving and without running either post-save hook (:316-319), and only then, when the write was conditional, touches the root's concurrency token before saving (:321-328, SEC-Common-77) so the save always produces a rootUPDATEfor a conditional write, otherwise saves (:330), logs, runsOnMutatedAsync, and returns the mutated aggregate (:332-335).- Attempt scope (
:41-46,:269-273): as on the create side, the unit of work is a parameter, so a handler whose write can lose a race can wrap the workflow in a retry loop and run each attempt against a fresh DI scope's unit of work.
- Declaration (
- Why it's built this way: the workflow existed before the generic write side did, and ADR-099 records that the missing pieces were a command and a handler generic enough to close over any aggregate, not the workflow itself. The paired-overload design is what let the mutation context and the skip-save short circuit be added additively: every existing subclass compiles and behaves exactly as before.
- Where it's used: as the base of MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType> (
:347), of the four-parameter DTO-returningMutateEntityHandlerBase<TCommand, TEntity, TIdentifierType, TEntityDTO>(:370), and of MutateEntityPayloadHandlerBase<TCommand, TEntity, TIdentifierType, TResultPayload> (:415). Every generic and hand-written aggregate write handler in ADC and Store reaches it through one of those three. Exercised by MutateEntityHandlerBaseTests and MutationContextTests.
CreateEntityHandler<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/CreateEntityHandler.cs:28· Level 9 · class (sealed)
- What it is: the ready-made create handler, CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO> with none of its hooks overridden. Closing this type over an aggregate's four types is the whole create registration; no subclass is needed at all.
- Depends on: its base class and the same three injected collaborators, forwarded through the primary constructor (
CreateEntityHandler.cs:29-32): IUnitOfWork, IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType> and IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>. Constraints repeat the base's (:33-36). - Concept reinforced, "sealed floor, open base". See CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO> for the workflow.
[Rubric §15, Best Practices & Code Quality]assesses whether the cheap path and the extensible path are distinguishable; here they are two types rather than one. This one issealedon purpose, and the doc says why (:14-20): the base, not this, is the extension point, so a create that needs a pre-map step, a module-specific log message, a post-commit publish or the manual-id retry loop reaches for the base instead of subclassing this. - Walkthrough: the entire type is a declaration with a semicolon body (
:28-36). There is no{ }block: every hook on the base is virtual and none is overridden, which is precisely the claim the type is making. - Why it's built this way: ADR-099 targets the scaffolded module where create, update and delete are the same lines every time; this type is the create verb of the one-call registration.
- Where it's used:
AddEntityCrudregisters it as the create slot withTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:82-84), so an aggregate whose create outgrows it registers its own handler before that call and keeps the generic pair for the other two verbs (:44-52). Helpdesk's Tickets module gets its create this way (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/DependencyInjection.cs:54), as does Store's Identity module forCustomer(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:65-67).
MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutateEntityHandlerBase.cs:347· Level 9 · class (abstract)
- What it is: the write handler over an existing aggregate that answers with a bare Result: the verb-style commands (publish, unpublish, open, close, moderate, rename, remove a child) where the caller needs only success or the refused invariant.
- Depends on: MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType> (base,
MutateEntityHandlerBase.cs:348), which it forwards the injected IUnitOfWork to; ICommandHandler<in TCommand, TResult> closed overResult(:321); AuditableAggregateRootEntity<TIdentifierType> (constraint,:322). - Concept reinforced, the return-shape split. The teaching for the workflow itself is under MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType>.
[Rubric §9, API & Contract Design]assesses what a use case hands back: this is the "nothing to render" answer, and choosing it rather than returning a DTO nobody reads is what keeps a verb endpoint from implying the caller should re-render from the response. - Walkthrough: the whole type is nine lines. The declaration (
:319-323) inherits the core and adds the handler interface.HandleAsync(:326-331) awaitsMutateCoreAsync(command, cancellationToken)and collapses theResult<TEntity>it returns into a bareResult: the errors on failure,Result.Success()otherwise, discarding the aggregate the core handed back. It isvirtual, which is the hook a subclass overrides to run a pre-flight check before the workflow (Store's inventory handlers do exactly that on the update side). - Why it's built this way: it is one of the three thin subclasses ADR-099 describes; splitting by return shape is what lets the core implement no handler interface and so avoid a duplicate registration during the module scan (
:16-27). - Where it's used: it is the most-subclassed write base in ADC. Conference uses it for
PublishEventHandlerandUnpublishEventHandler(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/Publish/PublishEventHandler.cs:16,.../Unpublish/UnpublishEventHandler.cs:16),UpdateRoomHandler(.../Events/UseCases/UpdateRoom/UpdateRoomHandler.cs:16),UpdateEventQuestionAnswerHandlerandRemoveEventQuestionAnswerHandler(.../UpdateEventQuestionAnswer/UpdateEventQuestionAnswerHandler.cs:24,.../RemoveEventQuestionAnswer/RemoveEventQuestionAnswerHandler.cs:24),UpdateCategoryItemHandler(.../Categories/UseCases/UpdateCategoryItem/UpdateCategoryItemHandler.cs:22), andLinkUserToSpeakerHandler/UnlinkUserFromSpeakerHandler(.../Speakers/UseCases/LinkUser/LinkUserToSpeakerHandler.cs:28,.../UnlinkUser/UnlinkUserFromSpeakerHandler.cs:28); Engagement uses it forModerateQuestionHandler,OpenLivePollHandlerandCloseLivePollHandler(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/SessionQuestions/UseCases/Moderate/ModerateQuestionHandler.cs:28,.../LivePolls/UseCases/Open/OpenLivePollHandler.cs:26,.../LivePolls/UseCases/Close/CloseLivePollHandler.cs:24); Identity uses it forRemoveUserAvatarHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RemoveUserAvatar/RemoveUserAvatarHandler.cs:22). It is also the base of RemoveChildEntityHandlerBase<TCommand, TParent, TIdentifierType> (ChildEntityHandlerBase.cs:181). Exercised by MutateEntityHandlerBaseTests. - Caveats / not-in-source: a four-parameter sibling declared in the same file,
MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType, TEntityDTO>(:342-359), is the DTO-returning flavor: it takes an IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType> beside the unit of work and maps the mutated aggregate on success (:358). Generic types overload by arity, so the two share a name; ADC'sUpdateQuestionHandleruses the four-parameter one (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Questions/UseCases/Update/UpdateQuestionHandler.cs:23).
RemoveChildEntityHandlerBase<TCommand, TParent, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/ChildEntityHandlerBase.cs:180· Level 10 · class (abstract)
- What it is: the shared remove-a-child-from-an-aggregate workflow. It is MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType> with exactly one change: the child collection becomes a required include.
- Depends on: MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType> (base,
ChildEntityHandlerBase.cs:181), to which it forwards the injected IUnitOfWork; AuditableAggregateRootEntity<TIdentifierType> (constraint,:144). Its workflow comes from MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType> two levels up. - Concept introduced,
abstract override: re-opening an inherited virtual member to force the subclass to answer.[Rubric §1, SOLID]and[Rubric §15, Best Practices & Code Quality]. C# lets a derived class re-declare an inheritedvirtualmember asabstract override, which removes the base's default and makes the member mandatory again for anything deriving further. That single line is this type's entire body (:151), and the reason is stated at:128-133: a remove that cannot see the collection cannot find the child, so it reports a wrongNotFoundinstead of removing anything. The base's emptyIncludesdefault is a silently wrong answer for this one workflow, so the type deletes it. Compare AddChildEntityHandlerBase<TCommand, TParent, TIdentifierType, TChild, TChildDTO>, which reaches the same outcome by declaringIncludesabstract from the start. - Walkthrough: the declaration (
:142-145) and one member.protected abstract override IEnumerable<string> Includes { get; }(:151) is the whole body. Everything else (EntityId,MutateAsync,LogMutated, the load-stamp-mutate-save sequence and the bare-Resultreturn) is inherited. The type doc gives the intended implementation shape (:134-138):MutateAsyncis a one-line call into the aggregate's remove method wrapped inTask.FromResult, and a remove whose command can also arrive addressed by the child's own id (with no parent id) overridesLoadAsyncto resolve the owning root. - Why it's built this way: it is a two-line type that buys a compile-time error instead of a runtime
NotFoundbug, on the one workflow where the eager-load is not an optimization. Part of the generic write-side family in ADR-099. - Where it's used: ADC's Conference module subclasses it for every child removal:
RemoveRoomHandler, which is the canonical shape (declaration atMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/RemoveRoom/RemoveRoomHandler.cs:18, the mandatoryIncludes => [nameof(Event.Rooms)]at:19,EntityIdat:22, andMutateAsyncas a singleTask.FromResult(entity.RemoveRoom(...))at:25-29), plusRemoveEventSpeakerHandler(.../RemoveEventSpeaker/RemoveEventSpeakerHandler.cs:16),RemoveCategoryItemHandler(.../Categories/UseCases/RemoveCategoryItem/RemoveCategoryItemHandler.cs:16) andRemoveSpeakerCategoryItemHandler(.../Speakers/UseCases/RemoveSpeakerCategoryItem/RemoveSpeakerCategoryItemHandler.cs:16). Exercised by ChildEntityHandlerBaseTests.
UpdateEntityCommandHandler<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/UpdateEntityHandler.cs:185· Level 10 · class
- What it is: the generic update handler for a derived command: an UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> subclass that carries state beside the request. It runs the same load-stamp-apply-save workflow but hands the whole command to an IEntityUpdateCommandApplier<TEntity, TUpdateRequest, TIdentifierType, in TCommand>.
- Depends on: IUnitOfWork, the command-aware applier, and IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>, all three primary-constructor injected (
UpdateEntityHandler.cs:186-188); the four-parameter DTO-returningMutateEntityHandlerBaseas its base (:189), and through it MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType>. - Concept reinforced, the derived-command path. See UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> for why a command is derived at all.
[Rubric §5, Vertical Slice]assesses whether one use case's extra requirement stays inside that slice: here the module declares its own command and its own applier in the slice folder, and the framework supplies the handler unchanged.[Rubric §11, Security]: the shape matters most where the extra state is a server-side decision, since puttingCallerIsOrganizeron the command rather than in the request DTO is what stops a crafted body from setting it. - Walkthrough
- Declaration (
:185-193): five type parameters, withTCommandconstrained to a subclass of the generic update command (:190). Because the base is closed overTCommanditself, the handler serves the derived type directly. HandlerName(:199):$"{nameof(UpdateEntityCommandHandler<,,,,>)}<{typeof(TCommand).Name}>", so several derived commands over one aggregate produce distinguishableNotFoundfailures.EntityId(:202-207) andRowVersion(:210-215): both null-guard and return the inheritedcommand.Idandcommand.RowVersion, which is what keeps the ADR-035 stamp working for a derived command with no extra code.MutateAsync(:218-223): overrides the context-aware overload, not the context-free one, and forwardsentity, the wholecommand, the run's MutationContext and the token toupdateApplier.ApplyAsync. That is the one behavioral difference from the two sibling handlers in this file: the applier can read the context and can callSkipSave()on it.
- Declaration (
- Why it's built this way: it is one of the five 2026-08-30 extensions in ADR-099, added so a command carrying route-derived or server-decided state no longer forces a hand-written handler. Registration and the validator bridge stay one call (
:172-178). - Where it's used:
AddEntityUpdate<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>registers it withTryAddScopedand bridges the derived command toIValidator<TUpdateRequest>(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:195-199). ADC's Conference module rides this path forSpeaker, pairingUpdateSpeakerCommandwithSpeakerUpdateApplier, which its registration test asserts (MMCA.ADC/Tests/Modules/Conference/MMCA.ADC.Conference.Application.Tests/ConferenceCrudRegistrationTests.cs:111,:114). MMCA.Common's ownWriteSideExtensionsTestscovers the registration, theTryAddprecedence and the validator bridge (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/UseCases/WriteSideExtensionsTests.cs:547,:558,:602).
UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/UpdateEntityHandler.cs:48· Level 10 · class
- What it is: the generic update handler for the plain (non-derived) command. It loads the aggregate, stamps the caller's concurrency token, hands the request to the module's IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>, saves only when the aggregate accepted the change, and answers with the refreshed DTO. It is the update counterpart of DeleteEntityHandler<TEntity, TIdentifierType>.
- Depends on: IUnitOfWork, the applier, and IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>, primary-constructor injected (
UpdateEntityHandler.cs:49-51); the four-parameter DTO-returningMutateEntityHandlerBase, closed over UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> (:52-56); AuditableAggregateRootEntity<TIdentifierType> and IBaseDTO<TIdentifierType> as constraints (:57-59). - Concept reinforced, unsealed generic plus a documented "no new hook needed" pattern.
[Rubric §1, SOLID]and[Rubric §15, Best Practices & Code Quality]. Like the delete handler it is left unsealed so a module can subclass it to declare theIncludesits aggregate's mutation needs or to add a[LoggerMessage]partial without giving up the shared workflow (:15-21). The interesting part is what the doc argues against adding (:22-32): a subclass that has to touch the aggregate after it is loaded and before the applier runs (the common case being ADR-035's second concurrency token,SetOriginalRowVersionon a tracked child row that a nested update addresses, which the base'sRowVersionhook cannot reach because that hook stamps the root) does not get a new hook. It overridesMutateAsync, does its work againstUnitOfWork.GetRepository<TEntity, TIdentifierType>(), then awaitsbase.MutateAsync(...)to run the applier: the aggregate is already loaded and already root-stamped, and a refusal returned before the base call stops the write.[Rubric §4, DDD]: no events are raised here (:33-37); a handler that published anything of its own would fire for the generic path and stay silent for a hand-written one. - Walkthrough
HandlerName(:65):nameof(UpdateEntityHandler<,,,>), the open handler name rather than the runtime backtick-4 suffixed one, so aNotFoundfailure reads the same as the hand-written handlers it replaces.EntityId(:68-73) andRowVersion(:76-81): null-guard and returncommand.Idandcommand.RowVersion. Note the return type narrows to non-nullablebyte[], matching the command's required token.MutateAsync(:84-92): overrides the context-free overload and returnsupdateApplier.ApplyAsync(entity, command.Request, cancellationToken), passing only the request. That is the whole difference from UpdateEntityCommandHandler<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>.- The verb-discriminated sibling (
:115-163): a five-parameterUpdateEntityHandlerthat serves the four-parameter command and injectsTApplierby its concrete type (:117), which resolves because the module scan registers an applier as itself as well as by its interfaces (:104-108). ItsHandlerNamefolds the applier name in (:133), so two verbs over one aggregate produce distinguishable failures.
- Why it's built this way: the update verb was the one every aggregate still hand-wrote, at roughly the same twelve lines each time, and ADR-099 closed it by pairing this handler with the generic command and the module-owned applier. The repository comes from the unit of work through the inherited workflow and is never constructor-injected, because only the unit of work knows which physical data source the aggregate resolves to (
:38-42). - Where it's used:
AddEntityCrudregisters it as the update slot withTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:86-88), andAddEntityUpdateVerbregisters the five-parameter sibling once per verb (:136-155). Subclassed where an aggregate needs an eager load: Helpdesk'sTicketUpdateHandleradds nothing butIncludes => [nameof(Ticket.Comments)](MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/Tickets/UseCases/Update/TicketUpdateHandler.cs:37,:41), and Store'sCategoryAssignParentUpdateHandlertakes the same route (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Categories/UseCases/AssignParentCategory/CategoryAssignParentUpdateHandler.cs:40). Store's inventory pair rides the verb-discriminated sibling and overridesHandleAsyncto run a cross-service existence guard before the workflow (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Inventory/UseCases/Adjust/IncreaseInventoryHandler.cs:44-65, and the decrease twin at.../DecreaseInventoryHandler.cs:29). Exercised byUpdateEntityHandlerTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/UseCases/Crud/UpdateEntityHandlerTests.cs:189).
MutateEntityPayloadHandlerBase<TCommand, TEntity, TIdentifierType, TResultPayload>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Crud·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutateEntityHandlerBase.cs:415· Level 14 · class (abstract)
- What it is: the third return-shape flavor of the mutate workflow, the write handler that answers with a payload of its own choosing rather than the aggregate's DTO: the refreshed DTO plus a warning the caller has to surface, a projection of one changed field, a receipt for the file the write replaced.
- Depends on: MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType> (base,
MutateEntityHandlerBase.cs:417), to which it forwards the injected IUnitOfWork; ICommandHandler<in TCommand, TResult> closed overResult<TResultPayload>(:410); MutationContext (:419,:438); AuditableAggregateRootEntity<TIdentifierType> (constraint,:411). - Concept introduced, an unconstrained result type plus a context that outlives the mutation.
[Rubric §9, API & Contract Design]assesses whether a use case can express an answer the resource DTO cannot.TResultPayloadcarries no constraint (:411-412), which is the whole point: the DTO flavor can only answer with anIBaseDTO<TIdentifierType>mapped by the aggregate's registered mapper, right for "the caller re-renders the aggregate" and wrong for everything else (:390-396).[Rubric §9, API & Contract Design]: the handler builds the answer itself and can read both the mutated aggregate and whatever the mutation wrote into the MutationContext while the aggregate was loaded, so a pre-mutation value can reach the response without handler instance state, which matters because handlers are scoped services and instance fields across an async workflow are a concurrency hazard. One naming note: it is a sibling of the other two rather than a fourth type parameter on the DTO flavor, because generic types overload by arity alone and a four-parameterMutateEntityHandlerBasealready exists (:399-400). - Walkthrough
- Declaration (
:407-412): four type parameters, the core as base, the command-handler interface closed overResult<TResultPayload>. HandleAsync(:415-426): creates the context itself withCreateContext()(:419), rather than letting the convenience overload create one, then calls the three-argumentMutateCoreAsync(UnitOfWork, command, context, ...)(:421) so the same context instance is still in hand after the workflow returns. It then branches onresult.TryGetValue(out var mutated): on failure it forwards the errors, on success it callsBuildResult(mutated, command, context)(:423-425). That is the mechanical reason this flavor exists as its own class: the other two never need the context back.BuildResult(:438): the single abstract member,protected abstract Result<TResultPayload> BuildResult(TEntity entity, TCommand command, MutationContext context). It is synchronous and returns aResult, so a payload that cannot be built is a failure value rather than an exception. It is called only on success, after the save, or after aSkipSaveshort circuit, where the aggregate is the one that was loaded and left untouched (:428-432).
- Declaration (
- Why it's built this way: it is one of the five extensions the 2026-08-30 revision of ADR-099 added to close the shapes that still forced a hand-written handler, and it is additive: every existing subclass of the other two flavors compiles and behaves exactly as before.
- Where it's used: ADC's
UpdateEventHandleris the reference case (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/Update/UpdateEventHandler.cs:23). ItsMutateAsynccompares the incoming timezone against the stored one beforeEvent.Updateoverwrites it, only pays for a session-existence lookup when the value actually moves, and writes the BR-131 warning flag into the context under a private key (:43-57);BuildResultthen assembles theUpdateEventResultenvelope from the aggregate plus that flag (:80). ADC also uses it forAddRoomHandler(.../Events/UseCases/AddRoom/AddRoomHandler.cs:28), forUpdateSessionHandler(.../Sessions/UseCases/Update/UpdateSessionHandler.cs:23) and forSetUserAvatarHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarHandler.cs:34). Exercised by MutateEntityHandlerBaseTests.
CqrsMetrics
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CqrsMetrics.cs:26· Level 0 · class (static, internal)
- What it is: an
internal staticclass that owns oneSystem.Diagnostics.Metrics.Meterand six instruments: two duration histograms (cqrs.command.duration,cqrs.query.duration), two cache counters (cqrs.query.cache.hit,cqrs.query.cache.miss), and two short-circuit counters (cqrs.authorization.denied.count,cqrs.timeout.count). The logging decorators record duration on every command and query; the caching query decorator records hit and miss; the authorization and timeout decorators record their denials and expiries. Together they give RED (Rate / Errors / Duration) instrumentation for the whole CQRS pipeline, plus a cache hit ratio and two short-circuit rates. - Depends on: BCL only (
System.Diagnostics.Metrics,CqrsMetrics.cs:1). Recorded into by LoggingCommandDecorator<TCommand, TResult>, LoggingQueryDecorator<TQuery, TResult>, CachingQueryDecorator<TQuery, TResult>, AuthorizationCommandDecorator<TCommand, TResult>, AuthorizationQueryDecorator<TQuery, TResult>, TimeoutCommandDecorator<TCommand, TResult>, and TimeoutQueryDecorator<TQuery, TResult>. - Concept introduced, BCL-native metrics and RED instrumentation.
[Rubric §13, Observability & Operability]assesses whether every unit of work emits rate, error, and latency signals an operator can dashboard and alert on. A single histogram tagged byoutcomesupplies all three dimensions at once: the measurement value is duration, the count is the rate, and the count filtered to a failureoutcomeis the error rate (the class doc says exactly this,CqrsMetrics.cs:6-10). UsingSystem.Diagnostics.Metricsrather than a third-party client means the OpenTelemetry SDK exports these once a host registers the meter name. The doc notes the meter name is duplicated as a literal string inMMCA.Common.Aspirebecause that package holds no reference to Application (CqrsMetrics.cs:8-10), and the literal is verifiably there:"MMCA.Common.Cqrs"in the AspireFrameworkMeterNameslist (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:64), second in a list of eleven meters that also covers Outbox, Idempotency, Scheduler, Broker, OutputCache, BestEffort, InternalCommands, Persistence, Auth, and the AI package's own meter (Extensions.Telemetry.cs:61-74), which the service defaults subscribe in onemetrics.AddMeter([.. FrameworkMeterNames])call (Extensions.Telemetry.cs:353). The two names agree today. The compiler does not enforce that, but the list's remarks state that a fitness test holds it equal to the meters the Common packages actually create (Extensions.Telemetry.cs:58-59). - Walkthrough
MeterName(CqrsMetrics.cs:29):internal const string = "MMCA.Common.Cqrs", the single name a host registers for export.Meter(CqrsMetrics.cs:31): aprivate static readonly Metercreated once at class initialization, so no instrument is re-registered per decorator instance.CommandDuration(CqrsMetrics.cs:34-37) andQueryDuration(CqrsMetrics.cs:40-43):internal static readonly Histogram<double>instruments namedcqrs.command.durationandcqrs.query.duration, unit"ms", each described as tagged by name and outcome.QueryCacheHits(CqrsMetrics.cs:46-49) andQueryCacheMisses(CqrsMetrics.cs:52-55):Counter<long>instruments namedcqrs.query.cache.hitandcqrs.query.cache.miss, unit"{query}". Charting one over their sum is the per-query hit ratio, which is how an operator spots a cache that has quietly stopped serving reads (CqrsMetrics.cs:11-19).AuthorizationDenied(CqrsMetrics.cs:58-61):Counter<long>namedcqrs.authorization.denied.count, unit"{request}", taggedrequest_type. It exists so a permission that is denying far more traffic than expected is visible as a metric rather than only as a client-side error rate (CqrsMetrics.cs:20-24).TimeoutExpired(CqrsMetrics.cs:64-67):Counter<long>namedcqrs.timeout.count, unit"{request}", taggedrequest_type, counting the commands and queries whose IHasTimeout budget expired before the handler completed.- Recording helpers (
CqrsMetrics.cs:71-72,:71-72,:76-77,:81-82):RecordCacheHit,RecordCacheMiss,RecordAuthorizationDenied,RecordTimeout, each a one-lineAdd(1, ...)with a single tag. Exposing methods rather than the raw counters keeps every tag name spelled once. - Visibility: everything is
internal, so only decorators in this assembly can record measurements and no external code can pollute the series.
- Why it's built this way: one static holder avoids the duplicate-instrument problem that would follow from each closed generic decorator creating its own meter, and the tag dimension (rather than one counter per outcome) is the idiomatic OpenTelemetry shape for RED. The two short-circuit counters arrived with the decorators that emit them, in the 2026-08-18 revision of ADR-014.
- Where it's used: LoggingCommandDecorator<TCommand, TResult> records
CommandDuration(LoggingCommandDecorator.cs:109-113); LoggingQueryDecorator<TQuery, TResult> recordsQueryDuration(LoggingQueryDecorator.cs:102-106); CachingQueryDecorator<TQuery, TResult> callsRecordCacheHitatCachingQueryDecorator.cs:77and:100andRecordCacheMissat:91and:110; the authorization decorators reachRecordAuthorizationDeniedthrough their shared AuthorizationGate (AuthorizationGate.cs:49, called fromAuthorizationCommandDecorator.cs:36andAuthorizationQueryDecorator.cs:31); the timeout decorators reachRecordTimeoutthrough their sharedTimeoutBudget.RunAsync(TimeoutBudget.cs:48, called fromTimeoutCommandDecorator.cs:39andTimeoutQueryDecorator.cs:39). - Caveats / not-in-source: the
outcometag values are set by the logging decorators, not here. They are"completed","failed", or"exception"(LoggingCommandDecorator.cs:50,:48,:57), a three-valued dimension rather than a bare success/failure pair. Note also the tag-name asymmetry: the duration histograms tagcommandandquerywhile the two short-circuit counters tagrequest_type, so a dashboard cannot join them on one label without a rename.
ProfilingCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ProfilingCommandDecorator.cs:12· Level 1 · class (sealed)
- What it is: a decorator that wraps command handler execution in a MiniProfiler step, so each command shows up as a timed node in a MiniProfiler trace.
- Depends on:
StackExchange.Profiling(NuGet, MiniProfiler,ProfilingCommandDecorator.cs:2); ICommandHandler<in TCommand, TResult> (both the inner handler it wraps and the interface it implements,ProfilingCommandDecorator.cs:12-13). - Concept introduced, opt-in profiling kept out of the standard pipeline.
[Rubric §13, Observability & Operability]assesses developer-facing profiling for pinpointing where time goes inside a request. This is the plain Decorator shape (a handler holding a handler), but unlike the seven standard command decorators it is not registered byAddApplicationDecorators()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:168-178). It is added only by the separateAddApplicationProfiling()extension (DependencyInjection.cs:237-243), so a host that never calls that method never pays for it. - Walkthrough:
HandleAsync(ProfilingCommandDecorator.cs:16) opensusing var step = MiniProfiler.Current?.Step($"CommandHandler: {typeof(TCommand).Name}")(ProfilingCommandDecorator.cs:18) and then awaits the inner handler (ProfilingCommandDecorator.cs:19). The null-conditional?.Step(...)makes the whole body a no-op when no MiniProfiler is ambient for the current request, so there is no measurable cost when profiling is off; the step name carries the command type name so the profile is readable. - Why it's built this way: keeping profiling in its own opt-in decorator (rather than folding it into the always-on logging decorator) means the profiler overhead and its ambient-profiler dependency exist only when a host explicitly turns it on. It is also the one extension that may legally be added after the pipeline is sealed:
AddApplicationProfiling()does not callThrowIfPipelineSealed, unlikeAddApplicationDecorators()(DependencyInjection.cs:147,:414-424). - Where it's used: registered by
AddApplicationProfiling()(DependencyInjection.cs:239) to wrap every command handler. Its counterpart middleware is wired in the API layer (see MiniProfilerExtensions). - Caveats / not-in-source:
AddApplicationProfiling()(DependencyInjection.cs:237) is called byAddMmcaServiceHostonly whenApplicationSettings:UseMiniProfileris true (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:162-165), and the flag is off by default, so a host carries this decorator only when its configuration turns profiling on.
ProfilingQueryDecorator<TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ProfilingQueryDecorator.cs:12· Level 1 · class (sealed)
- What it is: the query-side twin of ProfilingCommandDecorator<TCommand, TResult>. Same shape, one method, wrapping an IQueryHandler<in TQuery, TResult> (
ProfilingQueryDecorator.cs:12-13). - Depends on:
StackExchange.Profiling(NuGet,ProfilingQueryDecorator.cs:2); IQueryHandler<in TQuery, TResult>. - Concept reinforced: see ProfilingCommandDecorator<TCommand, TResult>.
[Rubric §13, Observability & Operability]. Also registered only by the opt-inAddApplicationProfiling()(DependencyInjection.cs:240), never by the standardAddApplicationDecorators(). - Walkthrough:
HandleAsync(ProfilingQueryDecorator.cs:16) opensMiniProfiler.Current?.Step($"QueryHandler: {typeof(TQuery).Name}")(ProfilingQueryDecorator.cs:18), a no-op when the profiler is inactive, then awaits the inner query handler (ProfilingQueryDecorator.cs:19). - Where it's used: registered by
AddApplicationProfiling()to wrap every query handler; like its command twin, it reaches a host only throughAddMmcaServiceHostwithApplicationSettings:UseMiniProfilerset.
TenantCacheKey
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TenantCacheKey.cs:25· Level 1 · class (static, internal)
- What it is: a two-member
internal statichelper that turns a cache key (or a cache prefix) into its tenant-scoped form. Both caching decorators run every key they touch through this one method, which is what keeps reads and invalidations pointing at the same entries. - Depends on: ITenantContext (
MMCA.Common.Application.Interfaces,TenantCacheKey.cs:1,:37). Nothing else, not even the cache abstraction: this type only computes strings. - Concept introduced, tenant isolation applied where the key is computed.
[Rubric §11, Security]assesses whether one customer's data can reach another;[Rubric §30, Compliance, Privacy & Data Governance]assesses tenant data boundaries. The problem the class doc states (TenantCacheKey.cs:9-14) is a lifetime mismatch:ICacheServiceis a singleton and cannot see the scoped tenant, so if two tenants both computed the cache keyproducts, the cache would happily serve one tenant's rows to the other. The framework's answer is not a tenant-aware cache but a tenant-aware key, computed once in one place so the query decorator's read and the command decorator's eviction cannot drift apart. The scoped form is deliberately a prefix, not a suffix (TenantCacheKey.cs:15-19), because prefix eviction is the invalidation primitive: evictingt:acme:productsremoves exactly that tenant's product entries, and no command in one tenant can evict another tenant's cache. Multi-tenancy as a whole is ADR-073, which is opt-in. - Walkthrough
Marker(TenantCacheKey.cs:28):internal const string Marker = "t:", the two-character opener of a scoped key. The doc comment gives the reason it is short: it is on every key (TenantCacheKey.cs:27).Scope(ITenantContext?, string)(TenantCacheKey.cs:37-40): the whole implementation is one expression. The patterntenantContext is { IsResolved: true, TenantId: { } tenantId }(TenantCacheKey.cs:38) tests three things at once: the context is not null (a host that never registered tenancy passesnull), it has resolved a tenant, andTenantIdis non-null, binding it in the same test. When all three hold it returnsstring.Concat(Marker, tenantId, ":", key); otherwise it returnskeyunchanged (TenantCacheKey.cs:39-40).
- Why it's built this way: the untouched-key fallback is the upgrade story (
TenantCacheKey.cs:20-23): a single-tenant host has byte-identical keys to the pre-tenancy framework, so upgrading orphans no cache entry and changes no behavior. Centralizing the transformation in oneinternal staticmethod rather than duplicating a$"t:{id}:{key}"interpolation in each decorator is what makes the symmetry argument checkable: there is exactly one function to read. - Where it's used: CachingQueryDecorator<TQuery, TResult> calls it from
EffectiveKey(CachingQueryDecorator.cs:57-58), whose one result is then used for the read, the stampede lock, and the populate; CachingCommandDecorator<TCommand, TResult> calls it on the command'sCachePrefixbefore eviction (CachingCommandDecorator.cs:106). - Caveats / not-in-source:
Scopedoes nothing to sanitizetenantIdorkey, so a tenant id containing:would produce an ambiguous key. Whether the tenant resolver can ever yield such an id is decided in ITenantContext's implementation, not here.
UserCacheKey
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/UserCacheKey.cs:26· Level 1 · class (static, internal)
- What it is: a one-method
internal statichelper that scopes a cache key to the calling user, the caller-scoped twin of TenantCacheKey. CachingQueryDecorator<TQuery, TResult> runs every key through it before applying the tenant scope, so a query addressed at one caller cannot return another caller's cached answer. - Depends on: IUserScopedRequest (
UserCacheKey.cs:39, suppliesUserId); ISharedQueryCache (the opt-out marker tested at:39). Nothing else, like TenantCacheKey this type only computes strings. - Concept introduced, per-caller cache scoping layered under tenant scoping.
[Rubric §11, Security]assesses whether one caller's cached answer can leak to another;[Rubric §30, Compliance, Privacy & Data Governance]assesses the same boundary for personal data. A query is caller-scoped when it implements IUserScopedRequest; CachingQueryDecorator<TQuery, TResult> composes this scope inside the tenant scope so the effective key carries both segments when both apply (CachingQueryDecorator.cs:58-59). A query can opt back out of caller scoping even while implementing IUserScopedRequest by also implementing ISharedQueryCache, the escape hatch for a query that filters by caller but whose result is safe to share across callers. - Walkthrough
Marker(UserCacheKey.cs:29):internal const string Marker = ":u:", kept short because, like TenantCacheKey's marker, it is on every key.Scope(object?, string)(UserCacheKey.cs:38-41): the patternquery is IUserScopedRequest userScoped and not UseCases.Markers.ISharedQueryCache(:39) tests both conditions at once, caller-scoped and not opted out. When it matches it returnsstring.Concat(key, Marker, userScoped.UserId.ToString(CultureInfo.InvariantCulture)); otherwise it returnskeyunchanged (:40-41).
- Why it's built this way: appending the user segment rather than prefixing it (as TenantCacheKey does with the tenant segment) keeps the two scopes independent and composable in a fixed order, the caller decides how:
EffectiveKeyin CachingQueryDecorator<TQuery, TResult> puts the tenant outermost. Theobject?parameter, rather than a generic constraint, is what lets one non-generic helper serve every closed CachingQueryDecorator<TQuery, TResult>, the same shape TenantCacheKey uses for the same reason. - Where it's used: CachingQueryDecorator<TQuery, TResult> calls it from
EffectiveKey(CachingQueryDecorator.cs:58-59), nested inside the TenantCacheKey call so tenant and caller scoping compose on every cached read. - Caveats / not-in-source: like TenantCacheKey,
Scopedoes not sanitize the composed key, so nothing here rejects aUserIdwhose string form contains the marker. Whether that can occur is decided by the identifier type backingUserId, not by this type.
RequestShape<T>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidationGate.cs:57· Level 1 · class (static, private, generic, nested in ValidationGate)
- What it is: a private nested generic holder inside ValidationGate with a single field,
WrapsRequest, that answers once per type whetherTembeds a request DTO by implementing ICommandWithRequest<out TRequest> (ValidationGate.cs:49-62). - Depends on: ICommandWithRequest<out TRequest> (
MMCA.Common.Application.UseCases.Contracts,usingatValidationGate.cs:3, its open generic definition tested at:61); BCL reflection (Type.GetInterfaces,Array.Exists). - Concept reinforced: the per-closed-type static cache introduced under ResultFailure<TResult>. A
staticfield on a generic class exists once per closed type, so the interface scan runs once for each validatedTand every later validation reads a precomputedboolwith no dictionary lookup.[Rubric §12, Performance & Scalability]assesses keeping per-request reflection off the hot path; here the reflection happens on first access per type, never per request. - Walkthrough:
WrapsRequest(ValidationGate.cs:59-61) is aninternal static readonly boolinitialized withArray.Exists(typeof(T).GetInterfaces(), i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandWithRequest<>)). Comparing generic type definitions is what makes the test independent of which request DTO the command carries. - Why it's built this way: the doc comment (
ValidationGate.cs:49-55) gives the reason the flag exists. Every validator over a request-wrapping command (the framework bridge and an explicit command validator that nests the request validator alike) reports request properties under aRequest.path, and the synthesized wire code drops that segment so a rule answers under one code whichever validator ran it. ValidationGate passes the flag toValidationFailureExtensions.ToGateErrorsasrequestWrapped(ValidationGate.cs:40-43;MMCA.Common/Source/Core/MMCA.Common.Application/Extensions/ValidationFailureExtensions.cs:80), which drops the leadingRequest.from a synthesized code only, so a default-coded rule answers asEmail.Requiredeither way whileError.Targetkeeps the full property path (ValidationFailureExtensions.cs:72-78). - Where it's used: only by ValidationGate's
ValidateAsync, asRequestShape<TRequest>.WrapsRequest(ValidationGate.cs:43). Beingprivate, nothing outside that class can reach it; the behavior it drives is exercised byValidationGateWireCodeTestsinMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/.
FeatureFlagGate
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/FeatureFlagGate.cs:12· Level 2 · class (static, internal)
- What it is: a one-method
internal statichelper holding the feature-flag check that both FeatureGateCommandDecorator<TCommand, TResult> and FeatureGateQueryDecorator<TQuery, TResult> delegate to. It answers one question: should this request be refused because its feature is off, and if so, with what Error. - Depends on: IFeatureGated (
MMCA.Common.Application.UseCases.Markers,FeatureFlagGate.cs:2, tested at:36);Microsoft.FeatureManagement.IFeatureManager(NuGet,FeatureFlagGate.cs:1,:34); Error (MMCA.Common.Shared.Abstractions,:3). - Concept introduced, one gate shared by the command and query twins.
[Rubric §12, Performance & Scalability]assesses centralized feature-flag enforcement;[Rubric §15, Best Practices & Code Quality]assesses whether duplicated logic is factored so it cannot diverge. The class doc states the purpose in one line: the check is shared "so the two cannot drift", the same shape as AuthorizationGate (FeatureFlagGate.cs:7-11). Both decorators therefore return the identical code and message for a disabled feature, by construction rather than by two copies of the same literal staying in sync. - Walkthrough:
EvaluateAsync(object? request, IFeatureManager featureManager)(FeatureFlagGate.cs:34) returnsTask<Error?>. The guard (:36-37) returnsnull(proceed) whenrequest is not IFeatureGated featureGated, or whenawait featureManager.IsEnabledAsync(featureGated.FeatureName)is true; the||short-circuits, so a request that is not gated never touches the feature manager. Otherwise it returnsError.NotFoundError("Feature.Disabled", "The requested feature is not currently available.")(:45-47). The comment (:42-44) records why the message is fixed and generic: it reaches the user verbatim, so it matches the wordingDisabledFeatureHandleruses for a[FeatureGate]endpoint and keeps the internal flag name out of it; clients branch on theFeature.Disabledcode. - Why it's built this way: returning a nullable
Errorrather than aTResultkeeps the helper non-generic, so it never needs to know the handler's result type; each decorator wraps the error into its own failure through ResultFailure<TResult>. Theobject?parameter is what lets one helper serve every closed command and query decorator. ReturningNotFoundrather thanForbiddenis the "this operation does not currently exist" answer described under FeatureGateCommandDecorator<TCommand, TResult>. - Where it's used: FeatureGateCommandDecorator<TCommand, TResult> (
FeatureGateCommandDecorator.cs:28) and FeatureGateQueryDecorator<TQuery, TResult> (FeatureGateQueryDecorator.cs:27), its only two callers.
CachingCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingCommandDecorator.cs:43· Level 3 · class (sealed, partial)
- What it is: the caching decorator on the command side. It caches nothing; it invalidates cached read data after a mutation, and only when the command opts in via ICacheInvalidating with a non-blank prefix. It evicts after a non-failure result and also after a handler that throws, never after a failure result, and it evicts twice: once immediately, once after a short delay.
- Depends on: ICacheInvalidating (the opt-in marker exposing
CachePrefix); ICacheService (the eviction mechanism); ITenantContext (optional, defaulted tonull) and TenantCacheKey (prefix scoping); ICommandHandler<in TCommand, TResult>; Result (pattern-matched to detect failure);Microsoft.Extensions.Logging. - Concept introduced, invalidate whenever the write may have landed, and best-effort at that.
[Rubric §12, Performance & Scalability]assesses whether write-side invalidation keeps read caches coherent without over-evicting;[Rubric §29, Resilience & Business Continuity]assesses what a dependency outage does to a request. Four invariants are stated in the class doc and enforced in code. (1) A failure result skips eviction (CachingCommandDecorator.cs:13-16): the mutation persisted nothing (a business failure also rolls the transaction back, see TransactionalCommandDecorator<TCommand, TResult>), so evicting valid entries would cost concurrent readers a needless miss. (2) A handler that throws still gets the eviction and its delayed follow-up, and the exception is then rethrown unchanged (:17-23): a post-save hook such asOnMutatedAsyncorOnCreatedAsyncruns after the save of a command that is not ITransactional, so the write may already have committed; when the throw instead rolled the write back, the eviction costs one cache miss. (3) Invalidation is non-cancellable and never propagates a fault (:24-33): a cache outage must not turn a committed command into a failure, and the one fault treated differently is anArgumentExceptionfrom a prefix the cache rejects, a bug in the command that is logged at error level and neither retried nor followed up. (4) Under multi-tenancy the prefix is scoped with the same transformation the query decorator applies to its keys (:34-39), which is the property that makes eviction hit exactly the entries this tenant's queries wrote. - Walkthrough
- Primary constructor (
CachingCommandDecorator.cs:43-47): inner handler, ICacheService, a typed logger, andITenantContext? tenantContext = null. The optional tenant parameter is what keeps the type resolvable in a host that never registered tenancy. ReInvalidationDelay(CachingCommandDecorator.cs:55): aninternal TimeSpanproperty, defaultTimeSpan.FromSeconds(5), settable so a test does not have to wait out the production delay (:49-54).InvalidationFollowUp(CachingCommandDecorator.cs:61): aninternal Taskwith a private setter, initialized toTask.CompletedTask, holding the most recent delayed eviction. It is exposed so the fire-and-forget task is observed rather than dropped, and so a test can await it deterministically (:57-60).HandleAsync(CachingCommandDecorator.cs:64): awaitsinner.HandleAsync(...)first, inside atry(:67-70), so the mutation always runs before any cache decision. A barecatch(:71-78) callsInvalidateAsync(command)(:76) and thenthrow;(:77), for the reason the comment gives (:73-75): the write may already have committed. On a normal return,!IsFailure(result)(:82) gates the sameInvalidateAsynccall (:84), and the result is returned unchanged (:87).InvalidateAsync(CachingCommandDecorator.cs:94): a private method documented as never throwing (:90-93), which is what lets the throw path rethrow the handler's original exception rather than a cache fault. Its guard (:98-99) returns early unlesscommand is ICacheInvalidating cacheInvalidatingandCachePrefixis not blank. The blank-prefix test is load-bearing and the comment says why (:96-97):RemoveByPrefixAsync("")would evict the entire cache, so an empty prefix is both an opt-out and a foot-gun guard.- Scoping (
CachingCommandDecorator.cs:106):TenantCacheKey.Scope(tenantContext, cacheInvalidating.CachePrefix). - First eviction (
CachingCommandDecorator.cs:112-113):RemoveByPrefixAsync(cachePrefix, CancellationToken.None). PassingNonerather than the request token is deliberate (:110-111): the command may have committed, so the cleanup must outlive a caller that has already walked away. - Misconfigured prefix (
CachingCommandDecorator.cs:115-122): anArgumentExceptionfrom the first eviction means the prefix breaks theRemoveByPrefixAsynccontract (it must end at a:boundary). The comment calls that a bug in the command, not a transient fault, so it is logged once throughLogMisconfiguredCachePrefixatError(:120, declared at:167-174, whose message tells the developer to fix the command'sCachePrefix) and the method returns (:121) without scheduling the delayed attempt, since it would fail identically. - Transient fault (
CachingCommandDecorator.cs:123-128): any other exception is caught (with an explicitCA1031suppression and a justification comment) and logged throughLogCacheInvalidationFailedatWarning(:127, declared at:158-165), whose message ends with the operational consequence: stale entries expire on their own TTL. - Delayed re-eviction (
CachingCommandDecorator.cs:136, implemented at:143-156): scheduled after thetry, so it runs whether the first eviction succeeded or failed transiently; the comment (:130-135) says a transient failure thereby gets its retry, and names the race it closes: a read that missed the cache before this command committed can still be running its handler against pre-write state and populate the entry after the first eviction, so a single eviction can leave a stale entry behind.ReInvalidateAfterDelayAsyncwaitsReInvalidationDelay(:147), evicts the same prefix again (:148), and swallows any failure into the sameWarninglog (:151-155). IsFailure(CachingCommandDecorator.cs:180-181):result is Shared.Abstractions.Result { IsFailure: true }, pattern matching becauseTResultis not constrained to aResulttype, so one test covers bothResultandResult<T>.
- Primary constructor (
- Why it's built this way: the command names what to evict (its
CachePrefix); the decorator plus ICacheService own how and when. Handlers stay free of cache-infrastructure knowledge, and the pipeline position (outside validation and outside the transaction, per ADR-014 and argued atDependencyInjection.cs:132-133) is what makes "after a committed mutation" true rather than aspirational. Evicting on a throw trades one possible needless miss (after a rollback) for never leaving a committed write's entries stale until their TTL. - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:174) around every command handler, but only when the host has opted into query caching (DependencyInjection.cs:165); it engages only for commands whoseTCommandimplements ICacheInvalidating, which is broadly adopted across ADC and Store write commands. - Caveats / not-in-source: the delayed re-eviction narrows the repopulate window but does not close it. A read whose handler runs longer than
ReInvalidationDelay(5 seconds) can still repopulate a stale entry after the second eviction; the code's own answer to that residue is the entry's TTL (CachingCommandDecorator.cs:32).InvalidationFollowUpis assigned once per invalidation that did not hit a misconfigured prefix (:136) and nothing in production code awaits it: it is observed by tests, and a host shutting down mid-delay simply loses it. And the barecatchat:71does not excludeOperationCanceledException, so a command the caller cancelled mid-handler also evicts (withCancellationToken.None) before the cancellation is rethrown; by the class doc's own reasoning that costs at most one cache miss.
QueryCacheKeyLocks
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:263· Level 2 · class (static, internal)
- What it is: a tiny
internal staticholder for the process-wide lock set used by CachingQueryDecorator<TQuery, TResult> for cache-stampede protection. It is declared at the bottom of the same file as the decorator and has one member: a KeyedSemaphoreStripe, a fixed-width set of pre-allocated semaphores that cache keys are hashed onto. - Depends on: KeyedSemaphoreStripe (
MMCA.Common.Shared.Concurrency,usingatCachingQueryDecorator.cs:7; BCLSemaphoreSlimunderneath). Consumed exclusively by CachingQueryDecorator<TQuery, TResult>. - Concept introduced, why a shared lock table must live in a non-generic class.
[Rubric §12, Performance & Scalability]assesses whether a cache guards against the stampede (thundering herd) in which many concurrent requests all miss a just-expired hot key and all run the expensive query at once. The lock has to be shared by every request for the same key, but the decorator is an open generic. Astaticfield on a generic type is per closed type, soCachingQueryDecorator<QueryA, ...>andCachingQueryDecorator<QueryB, ...>would each get their own lock set and never serialize against each other on a shared key. Hoisting the field into this non-generic holder (the doc comment states exactly this rationale,CachingQueryDecorator.cs:242-246) gives every closed decorator one table. - Walkthrough:
Locks(CachingQueryDecorator.cs:266) isinternal static readonly KeyedSemaphoreStripe Locks = new(), the default-width stripe set:KeyedSemaphoreStripe.DefaultWidthis 256 (MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:25) and every semaphore is allocated up front in the constructor asnew SemaphoreSlim(1, 1)(KeyedSemaphoreStripe.cs:43-46). Keys are bucketed, not distinguished: the stripe index folds a string hash onto a fixed width, so two unrelated cache keys can land on the same stripe and briefly serialize against each other. A caller takes a stripe withawait Locks.AcquireAsync(key, cancellationToken)(KeyedSemaphoreStripe.cs:60) and releases it by disposing the returned Releaser handle (KeyedSemaphoreStripe.cs:78). There is no add or remove lifecycle at all: nothing is inserted on a miss, nothing is evicted on release, and the stripes are never disposed because the holder lives for the process. - Why it's built this way: the remarks (
CachingQueryDecorator.cs:248-254) name the defect this shape avoids. One semaphore per key in aConcurrentDictionaryforces a choice between two bugs: removing the entry when the last holder releases opens a window in which one caller waits on a semaphore that is no longer in the table while a second caller creates a fresh one (both then run concurrently, defeating the lock), and never removing it lets a cache key that embeds a user id or a filter value grow the table without bound. A fixed-width stripe set has neither problem, and the collision it introduces is harmless for a double-check-locking caller, which re-reads its own key's cache entry after acquiring (CachingQueryDecorator.cs:100-105). It is the same primitive and the same double-check pattern that IdempotencyFilter falls back on; the caching strategy as a whole is ADR-026. - Where it's used: only by CachingQueryDecorator<TQuery, TResult>, which reaches the stripe through its private
TryAcquirePopulateLockAsynchelper (CachingQueryDecorator.cs:185,:189) rather than callingAcquireAsyncinline, because the wait is now optionally time-boxed. The key passed in is the tenant-scoped one, so tenants do not queue behind each other by accident (CachingQueryDecorator.cs:69-71). - Caveats / not-in-source: the lock is per-process (
CachingQueryDecorator.cs:255-261). Across several app instances sharing one distributed cache, stampede protection is best-effort: at most one handler execution per instance, not one cluster-wide. The remarks call that duplication harmless (equal content, last write wins) and state that a cluster-wide guarantee would need a distributed lock and is deliberately not attempted here.
LoggingCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/LoggingCommandDecorator.cs:18· Level 3 · class (sealed, partial)
- What it is: the observability decorator on the command side. It opens a correlated logging scope carrying the command name, its owning module, and the correlation id, times the inner pipeline, logs start / completion / failure / caller cancellation / exception, and records the duration into CqrsMetrics. In the standard pipeline it is the fourth-outermost command decorator, just inside ViewAs, FeatureGate and Authorization (
MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:92-95). - Depends on: CqrsMetrics; ICorrelationContext (supplies
CorrelationId,LoggingCommandDecorator.cs:20,:27); ModuleNameConventions (MMCA.Common.Shared.Conventions,:107); QueryTagScope (opens the ambient query tag,:32); ICommandHandler<in TCommand, TResult>; Result (pattern-matched to detect failure);Microsoft.Extensions.LoggingandSystem.Diagnostics(BCL). - Concept introduced, structured logging plus metrics as a single cross-cutting stage.
[Rubric §13, Observability & Operability]assesses whether every command emits correlated, structured logs and a latency/outcome metric with no per-handler boilerplate;[Rubric §12, Performance & Scalability]assesses factoring that out of business logic. Every command that reaches it is logged and measured uniformly whether or not it is cached, validated, budgeted, or transactional, because this decorator sits above all of those in the chain. Its placement inside the feature gate is deliberate, so it only measures enabled-feature executions (DependencyInjection.cs:126).[Rubric §12, Performance & Scalability]also applies: the hot path uses the[LoggerMessage]source generator, a source-generated scope, a rawStopwatchtimestamp instead of aStopwatchinstance, and a per-closed-type static for the module name, so it avoids message interpolation, per-call dictionary boxing, one allocation per command, and a namespace parse per execution. - Walkthrough
- Names and correlation (
LoggingCommandDecorator.cs:26-27):typeof(TCommand).NameandcorrelationContext.CorrelationId, both read once. - Query tag (
LoggingCommandDecorator.cs:29-32):using (QueryTagScope.Begin(commandName))publishes the same command name the log scope carries as the ambient query tag, so any SQL the handler generates several awaits later names this use case in a query store. The comment is explicit that it is the command type, notinner.GetType(), sinceinneris the next decorator in the chain, never the handler. - Scope (
LoggingCommandDecorator.cs:33):using (BeginCommandScope(logger, commandName, ModuleName, correlationId))opens a structured scope so inner decorators and the handler shareCommandName,ModuleName, andCorrelationId.BeginCommandScopeis astatic readonly Func<ILogger, string, string, string, IDisposable?>built fromLoggerMessage.DefineScope<string, string, string>(LoggingCommandDecorator.cs:98-100), the allocation-light alternative to an anonymous-dictionaryBeginScope(the comment at:94-97says so). ModuleName(LoggingCommandDecorator.cs:107):ModuleNameConventions.GetModuleName(typeof(TCommand)) ?? "unknown", aprivate static readonly string. Because the field lives on a generic type it is computed once per closedTCommand(the comment at:102-106states exactly that), which is what makes a per-module log filter free at execution time. The"unknown"fallback keeps a command outside the module namespace convention loggable rather than throwing.- Start (
LoggingCommandDecorator.cs:35):LogCommandStartedatDebug(LoggingCommandDecorator.cs:117-118), deliberately notInformation. The comment (:115-116) gives the reason: the completion line already carries name and duration, and twoInformationrows per command doubles ingestion cost for no diagnostic gain. - Timing (
LoggingCommandDecorator.cs:40):Stopwatch.GetTimestamp(), withStopwatch.GetElapsedTime(startTimestamp)computed in each branch (:44,:66,:73). The comment (:37-39) records both the motive (one fewer allocation than aStopwatchinstance, same resolution) and the invariant it preserves: elapsed is captured before logging, so the recorded duration excludes the logging itself. - Failure branch (
LoggingCommandDecorator.cs:46-51): onResult { IsFailure: true }it joinsErrorsinto a"{Code}: {Message}"summary, logsLogCommandFailedatWarning(:123-124), and records the duration with outcome"failed". A business failure is aWarning, not anError: it is an expected outcome, not a defect. - Success branch (
LoggingCommandDecorator.cs:52-56):LogCommandCompletedatInformation(:120-121) and outcome"completed". - Cancellation branch (
LoggingCommandDecorator.cs:60-70):catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)(:60) handles a caller that cancelled (a client disconnect, a host shutdown). The comment (:62-65) says that is not a failure of the command, so it logsLogCommandCancelledatDebug(:67, declared at:133-134, "routine traffic, not an outcome an operator acts on",:132), records outcome"cancelled"(:68) rather than inflating the exception outcome, and rethrows (:69). The filter is on the caller's own token, so a timeout budget's expiry still falls through to the exception branch. - Exception branch (
LoggingCommandDecorator.cs:71-90): recomputes elapsed, then logsLogCommandExceptionatWarning, notError(:129-130), passingex.GetType().Namerather than the exception object itself, records outcome"exception"(:88), and rethrows (:89) so no decorator swallows a fault. The inline comment (:75-81) states why: the exception propagates untouched to a boundary (GlobalExceptionHandler, or the internal-command processor for a deferred command) that logs it once atErrorwith its full stack; logging it again here atErrorwould produce twoErrorrows and two stacks per unhandled exception, doubling ingestion cost for the noisiest events in the system and making an operator countingErrors count each failure twice. The sharedCorrelationIdis what joins thisWarningrow to the boundary'sErrorrow. RecordDuration(LoggingCommandDecorator.cs:109-113): the one place that touchesCqrsMetrics.CommandDuration, taggingcommandandoutcome.
- Names and correlation (
- Why it's built this way:
partial classplus[LoggerMessage](LoggingCommandDecorator.cs:117-134) is the .NET-recommended high-performance structured-logging shape, and the four-valuedoutcometag ("completed","failed","cancelled","exception") lets one histogram separate success from domain failure from a walked-away caller from a genuine exception on a dashboard. Carrying the module in the scope rather than in each message is what lets a modular-monolith operator slice every log line a handler emitted by the module that owns it, which is the property that survives extracting that module into its own service (ADR-007). Demoting the exception row toWarningand dropping the exception object (:126-128) is what keeps this decorator's own outcome record from duplicating the boundary's singleError-level stack, per ADR-014. - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:173), fourth in the outermost-first command list (:168-178, seven entries, or eight when the host opts into query caching), which makes it the fourth-outermost wrapper on every command handler:DecorateInExecutionOrderapplies the list innermost first so the first entry ends up outermost at runtime (DependencyInjection.cs:403-407). - Caveats / not-in-source: the outcome is recorded per branch, not in a
finally, and only a cancellation of the caller's own token lands in"cancelled". AnOperationCanceledExceptionraised for any other reason (a TimeoutCommandDecorator<TCommand, TResult> budget expiring, say) lands in the"exception"bucket like any other throw. Note also what this decorator does not see: a command short-circuited by ViewAsCommandDecorator<TCommand, TResult>, by the feature gate, or by AuthorizationCommandDecorator<TCommand, TResult> never reaches it, so those rejections appear only in their own counters, not incqrs.command.duration. And note the tag/log split:QueryTagScopeandBeginCommandScopeare two separateusingblocks, both keyed oncommandName, so a query-store tag and a structured log scope stay in sync without sharing a type.
LoggingQueryDecorator<TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/LoggingQueryDecorator.cs:16· Level 3 · class (sealed, partial)
- What it is: the query-side twin of LoggingCommandDecorator<TCommand, TResult>: correlated scope (query name, module, correlation id), timestamp-based timing, completion / failure / caller cancellation / exception logging, and a CqrsMetrics duration recording.
- Depends on: CqrsMetrics; ICorrelationContext; ModuleNameConventions; QueryTagScope (opens the ambient query tag,
:30); IQueryHandler<in TQuery, TResult>; Result;Microsoft.Extensions.Logging,System.Diagnostics. - Concept reinforced: see LoggingCommandDecorator<TCommand, TResult>.
[Rubric §13, Observability & Operability]and[Rubric §12, Performance & Scalability]. - Walkthrough:
HandleAsync(LoggingQueryDecorator.cs:22) opensusing (QueryTagScope.Begin(queryName))(:30), publishing the query name as the ambient query tag several awaits before the handler runs any SQL, the same pattern and rationale as the command side (:27-29); the query type is used, notinner.GetType(). It then opensBeginQueryScope(logger, queryName, ModuleName, correlationId)(:31), a source-generatedLoggerMessage.DefineScope<string, string, string>(:91-93) whoseModuleNameis the same per-closed-type static the command side uses (:100, rationale at:95-99), and times the inner handler from aStopwatch.GetTimestamp()(:36,:40), capturing elapsed before logging so the recorded duration excludes the logging itself (comment:33-35). The branch structure matches the command side exactly:Result { IsFailure: true }produces an error summary,LogQueryFailedatWarning(:111-112) and outcome"failed"(:42-47); success logsLogQueryCompletedatDebug(:108-109) and outcome"completed"(:48-52); a caller cancellation, filtered on the query's own token (:56), logsLogQueryCancelledatDebug(:63, declared at:121-122), records"cancelled"(:64) and rethrows (:65), while a timeout budget's expiry still falls through to the exception branch (comment:58-61); an exception recomputes elapsed (:69) and logsLogQueryExceptionatWarning, notError(:117-118), passingex.GetType().Namerather than the exception object, for exactly the reason the command side gives (a singleError-level stack belongs to the boundary that finally handles the rethrow, not to this decorator), records"exception", and rethrows (:67-82).RecordDuration(:102-106) writesCqrsMetrics.QueryDurationtaggedqueryplusoutcome. Two differences from the command side are worth noting: query completion logs atDebug(LoggingQueryDecorator.cs:108), notInformation, since reads are far more frequent than writes, and there is no "started" log line at all, so a query emits one row per execution. - Why it's built this way: the scope comment (
LoggingQueryDecorator.cs:86-90) records the reason it matches the command decorator rather than using a dictionary: aBeginScope(new Dictionary<string, object>)payload would cost a dictionary allocation and boxing on every query, and the source-generated scope avoids that while keeping the same structured keys. The exception log's demotion toWarningwithout the exception object mirrors LoggingCommandDecorator<TCommand, TResult> for the same reason: oneError-level stack per unhandled exception, logged once at the boundary, joined to this row byCorrelationId(:114-116). - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:185) to wrap every query handler, immediately inside AuthorizationQueryDecorator<TQuery, TResult> and the feature gate.
ResultFailureFactory
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ResultFailureFactory.cs:11· Level 3 · class (static, internal)
- What it is: an
internal statichelper that builds a delegate turning anIEnumerable<Error>into aTResultfailure, working for both non-generic Result and genericResult<T>, without constraining the caller'sTResult. - Depends on: Result and Error (
MMCA.Common.Shared.Abstractions,ResultFailureFactory.cs:2); BCLSystem.Linq.Expressions(:1) andSystem.Reflection(used fully qualified at:31). - Concept introduced, short-circuiting an unconstrained generic pipeline.
[Rubric §15, Best Practices & Code Quality]assesses how cleanly the codebase solves an awkward generic problem. The decorators need to fail a handler call without running the inner handler, but theirTResultis an open type parameter that is eitherResultorResult<T>; you cannot writereturn Result.Failure<T>(...)when you do not knowT. ConstrainingTResult : Resultwould change the handler interface contract for every handler in both apps, so instead this factory isolates the reflection to one place and, for the generic branch, compiles it into a delegate so the per-call cost is a plain invocation rather thanMethodInfo.Invoke(the doc comment states this,ResultFailureFactory.cs:16-17). - Walkthrough
Build<TResult>()(ResultFailureFactory.cs:20): the single entry point, returningFunc<IEnumerable<Error>, TResult>.- Non-generic branch (
ResultFailureFactory.cs:22-25): whentypeof(TResult) == typeof(Result), returnserrors => (TResult)(object)Result.Failure(errors). The double cast throughobjectis what the compiler requires with an unconstrainedTResult. - Generic branch (
ResultFailureFactory.cs:27-41): whenTResultis a closedResult<>, it takes the inner type (:29), reflects the public staticResult.Failureoverload that is a generic method definition with a singleIEnumerable<Error>parameter (:30-35), closes it over the inner type withMakeGenericMethod(:36), then builds and compilesExpression.Lambda<Func<IEnumerable<Error>, TResult>>(Expression.Call(failureMethod, errorsParam), errorsParam)(:38-40). The overload filter is specific on purpose: matching on name alone would be ambiguous acrossResult.Failure's overload set. - Guard (
ResultFailureFactory.cs:43-45): any otherTResultthrowsInvalidOperationExceptionnaming the unsupported type and the two it does support.
- Why it's built this way: compiling the expression once per closed type keeps the short-circuit path reflection-free after the first build, and centralizing the one piece of generic reflection keeps the decorators that need it readable.
- Where it's used: its one caller is ResultFailure<TResult>, which builds the delegate on first use and caches it per closed type (
ResultFailure.cs:26-27). Every short-circuiting decorator goes throughResultFailure<TResult>.From: FeatureGateCommandDecorator<TCommand, TResult> (FeatureGateCommandDecorator.cs:31), FeatureGateQueryDecorator<TQuery, TResult> (FeatureGateQueryDecorator.cs:30), ValidatingCommandDecorator<TCommand, TResult> (ValidatingCommandDecorator.cs:53), ValidatingQueryDecorator<TQuery, TResult> (ValidatingQueryDecorator.cs:56), AuthorizationCommandDecorator<TCommand, TResult> (AuthorizationCommandDecorator.cs:40) and its query twin (AuthorizationQueryDecorator.cs:35), ViewAsCommandDecorator<TCommand, TResult> (ViewAsCommandDecorator.cs:31), and the sharedTimeoutBudgetbehind both timeout decorators (TimeoutBudget.cs:50). - Caveats / not-in-source: the guard throw is the reason the delegate is built lazily rather than in a static initializer. A handler whose
TResultis neitherResultnorResult<T>is legal against ICommandHandler<in TCommand, TResult>, and an eager build would turn that into aTypeInitializationExceptionat DI resolve time, because the pipeline decorates every handler unconditionally (ResultFailure.cs:11-15).
ValidationGate
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidationGate.cs:12· Level 3 · class (static, internal)
- What it is: a one-method
internal statichelper that runs every FluentValidation validator registered for a request and collects the failures as Error values. It is the validation pass shared by ValidatingCommandDecorator<TCommand, TResult> and ValidatingQueryDecorator<TQuery, TResult>, "so the two cannot drift" (ValidationGate.cs:8-11). It also nests the private RequestShape<T> holder that tells it whether the validated type wraps a request DTO. - Depends on:
FluentValidation.IValidator<T>(NuGet,ValidationGate.cs:1,:24); ValidationFailureExtensions (MMCA.Common.Application.Extensions,:2, suppliesToGateErrorsat:40-43); ICommandWithRequest<out TRequest> (MMCA.Common.Application.UseCases.Contracts,:3, tested by RequestShape<T>); Error (MMCA.Common.Shared.Abstractions,:4). - Concept introduced, sequential validation because validators may touch the database.
[Rubric §15, Best Practices & Code Quality]assesses factoring a shared rule into one place;[Rubric §12, Performance & Scalability]assesses concurrency trade-offs made on purpose. The comment (ValidationGate.cs:27-29) states the one non-obvious decision: the validators run one after another, not concurrently, because a validator is free to reach the database through a scoped repository and aDbContextis not thread-safe. Running the set in parallel would trade a correctness guarantee for a saving measured in microseconds. - Walkthrough:
ValidateAsync<TRequest>(TRequest request, IValidator<TRequest>[] validators, CancellationToken cancellationToken)(ValidationGate.cs:22-25) returnsTask<List<Error>?>. It starts witherrors = null(:30), awaits each validator'sValidateAsync(request, cancellationToken)in aforeach(:31-33), skips a valid result (:34-37), and on the first failure lazily allocates the list (errors ??= [],:39) before appendingValidationFailureExtensions.ToGateErrors(validationResult, typeof(TRequest).Name, RequestShape<TRequest>.WrapsRequest)(:40-43). Each error therefore carries the request type name as its source, and whenTRequestwraps a request DTO its synthesized wire code drops the leadingRequest.path segment, so a rule answers under one code whichever validator ran it (see RequestShape<T>). It runs every validator rather than stopping at the first failure, so the caller sees the full set of problems at once. It returns the list, ornullwhen every validator passed (:46). - Why it's built this way: the
nullreturn for the all-valid case means the happy path allocates no list at all, and the caller's test is a single null check. Keeping the helper free ofTResult(it returns errors, not a failed result) lets each decorator wrap the list itself through ResultFailure<TResult>. Computing the request-wrapping flag in a per-type static holder (RequestShape<T>,ValidationGate.cs:57-62) keeps the interface scan off the per-request path. - Where it's used: ValidatingCommandDecorator<TCommand, TResult> (
ValidatingCommandDecorator.cs:46, wrapping the result at:53) and ValidatingQueryDecorator<TQuery, TResult> (ValidatingQueryDecorator.cs:49, wrapping at:56).
CachingQueryDecorator<TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:43· Level 4 · class (sealed, partial)
- What it is: the read-caching decorator. On a cache hit it returns the stored result without touching the inner handler; on a miss it runs the handler once (under a per-key lock, with an optional bound on how long a waiter waits for that lock) and caches the non-failure result. It engages only for queries that opt in via IQueryCacheable, and it never lets a cache fault fail a query.
- Depends on: IQueryCacheable (exposes
CacheKeyplusCacheDuration); ICacheService; IQueryHandler<in TQuery, TResult>; QueryCacheKeyLocks (the shared stripe table) and KeyedSemaphoreStripe; TenantCacheKey, UserCacheKey, and ITenantContext (optional); QueryCachePipelineSettings viaIOptions<T>(optional); CqrsMetrics; Result;Microsoft.Extensions.LoggingandMicrosoft.Extensions.Options. - Concept introduced, stampede protection by per-key double-check locking, and a fail-open cache.
[Rubric §12, Performance & Scalability]assesses read-side caching and, critically, what happens when a hot key expires under load: a naive cache lets every concurrent request miss and all run the expensive query at once.[Rubric §29, Resilience & Business Continuity]assesses degradation under a dependency outage. The class doc states the fail-open principle plainly (CachingQueryDecorator.cs:18-26): the cache is an optimization, never the system of record, so a cache outage must degrade the application to uncached reads rather than turn every cacheable query into a 500. Both the read and the populate log and swallow the fault, andOperationCanceledExceptionis deliberately excluded from each guard so a genuinely cancelled request still surfaces exactly as the inner handler would. The doc extends the same principle to the lock itself (:33-38): the wait is bounded byCache:PopulateLockTimeout, and a waiter that gives up runs the query rather than failing. - Walkthrough
- Constructor (
CachingQueryDecorator.cs:43-48): the inner handler,ICacheService, a typed logger,ITenantContext? tenantContext = null, andIOptions<QueryCachePipelineSettings>? pipelineSettings = null. Both optional parameters default tonull, which is what keeps the decorator resolvable in a host that registered neither tenancy nor the cache options. EffectiveKey(CachingQueryDecorator.cs:58-59):TenantCacheKey.Scope(tenantContext, UserCacheKey.Scope(cacheable, cacheable.CacheKey)). The doc comment (:50-55) states how the two segments compose: the query's own key is suffixed with the target user when the query is caller-scoped via UserCacheKey (the inner call), and the result is then prefixed with the tenant when one is resolved via TenantCacheKey (the outer call), so two tenants and two users never share an entry. The class doc spells out the tenant prefix ast:{tenantId}:and explains why isolation lives here rather than in the cache:ICacheServiceis a singleton and cannot see the scoped tenant (:27-32). A host with neither tenancy nor a caller-scoped query keeps byte-identical keys to the pre-tenancy framework.- Opt-out (
CachingQueryDecorator.cs:64-65):query is not IQueryCacheableshort-circuits straight to the inner handler, so non-cacheable queries pay one type test. - One key for three operations (
CachingQueryDecorator.cs:69-71): the comment states the invariant, read, stampede lock, and populate must all use the same tenant- and caller-scoped key, or one tenant (or one caller) would wait on another's lock and read another's entry. - Fast path (
CachingQueryDecorator.cs:74-79): a lock-freeTryReadAsyncthat returns a(found, cached)pair; whenfoundis true it recordsCqrsMetrics.RecordCacheHit(queryName)(:77) and returnscached!with no lock taken. - Lock budget (
CachingQueryDecorator.cs:84-85):pipelineSettings?.Value.PopulateLockTimeout ?? QueryCachePipelineSettings.DefaultPopulateLockTimeout. The default isTimeout.InfiniteTimeSpan(MMCA.Common/Source/Core/MMCA.Common.Application/Settings/QueryCachePipelineSettings.cs:29), so out of the box the wait is unbounded and exactly one request per key populates the entry. - Acquire or degrade (
CachingQueryDecorator.cs:87-96):TryAcquirePopulateLockAsyncreturnsnullwhen the budget elapsed first. That branch is fail-open by design (:90-92): it logsLogPopulateLockTimedOutatDebug(call:93, message at:156-163), records a miss (:94), runs the inner handler, and deliberately does not cache the result, because the request holding the lock is the one that populates the entry. - The lock itself (
CachingQueryDecorator.cs:179-198): with a non-positive timeout it awaitsQueryCacheKeyLocks.Locks.AcquireAsync(cacheKey, cancellationToken)and allocates nothing (:184-185); otherwise it arms a linked source (:187-188) and waits onbudget.Token(:192). The catch filterwhen (budget.IsCancellationRequested && !cancellationToken.IsCancellationRequested)(:194) is what separates an elapsed budget (returnnull, degrade) from a genuinely cancelled request (rethrow), the same split TimeoutQueryDecorator<TQuery, TResult> makes and the remarks name (:168-174). - Double-check (
CachingQueryDecorator.cs:98-105): insideusing (stripe)it re-reads; a waiter that arrived while the leader populated records a hit (:103) and returns the fresh entry without re-running the query. - Miss accounting (
CachingQueryDecorator.cs:113): the comment (:107-112) explains why the miss is counted here rather than at either read: a request that misses the fast path, takes the lock and misses the double-check has read the cache twice but executed once, so counting at the reads would double-count it. A read that failed also lands here and counts as a miss, which is correct because the query went uncached either way. - Populate (
CachingQueryDecorator.cs:115-134): the leader runsinner.HandleAsync(...)(:115), then stores viaSetAsync(cacheKey, result, cacheable.CacheDuration, cancellationToken)(:122-123) only when the result is notResult { IsFailure: true }(:118), so failures are never cached. TheSetAsyncis wrapped intry/catch (Exception ex) when (ex is not OperationCanceledException)(:125) and a failure logsLogCachePopulateFailedatWarning(:130, message at:138-145) while still returning the handler's answer. TryReadAsync(CachingQueryDecorator.cs:217-239): the fail-open read, returning(bool Found, TResult? Value). Presence is reported separately from the value because of value types, as the remarks explain (:204-212):ICacheService.GetAsync<T>answers a miss withdefault(TResult), which for abool, anintor a record struct is nevernulland would be served as a hit. So a value-typeTResultreads throughICacheService.TryGetAsync<T>(:224-228), while a reference type keepsGetAsync<T>withnullas the unambiguous miss (:230-232), which also spares the two-level store its presence probe. TheIsValueTypetest is a constant per closed decorator. A cache fault logsLogCacheReadFailedatWarning(:236, message at:147-154) and returns(false, default)(:237), which the caller treats as a miss; cancellation is again excluded from the catch filter (:234).
- Constructor (
- Why it's built this way: per-query
CacheKeyandCacheDurationowned by the query, plus stampede-safe locking and fail-open cache calls, gives a correct application-layer read cache that cannot become a new single point of failure. Keeping the stripe table in the non-generic QueryCacheKeyLocks is what lets all closed decorators share one lock per key. The lock timeout lives in QueryCachePipelineSettings rather than in Infrastructure's own cache settings for a layering reason the settings doc states (QueryCachePipelineSettings.cs:3-7,:9-14): this decorator is an Application-layer type and Application cannot reference Infrastructure, so the Application layer binds its own view of the sameCacheconfiguration section and the two cannot drift. - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:186), directly outside ValidatingQueryDecorator<TQuery, TResult> and therefore third-innermost on the read side. That position is what makes a cache hit skip validation and the budget entirely (DependencyInjection.cs:128-131,:136-137). In the production apps it engages for no query today: ADC has no IQueryCacheable implementor (its one hot public read,GetNowNextQuery, opts out on purpose and relies on a Redis-backed output-cache policy instead,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/NowNext/GetNowNextQuery.cs:10-12), and a search ofMMCA.Store/Sourcefinds none either, so for both this decorator is a pass-through. The framework's ownExportUserDataHandlerBasedoes not reach it either (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:55-56). The adopter is the Helpdesk reference app (GetTicketByIdQuery). Production read caching is otherwise done at the HTTP edge with output caching (the two-tier model of ADR-026). - Caveats / not-in-source: the same file also declares the QueryCacheKeyLocks holder below the class (
CachingQueryDecorator.cs:263), documented as its own type in this group. The stampede lock protects one process only; see the caveat under QueryCacheKeyLocks. And note the accounting consequence of the timeout branch: a query whose waiters give up records one miss per waiter (:94) plus one for the leader (:113), so under a configured finitePopulateLockTimeoutthe hit ratio understates how well the cache is working.
ResultFailure<TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ResultFailure.cs:19· Level 4 · class (static, internal, generic)
- What it is: an
internal staticgeneric class that turns a set of Error values into a failedTResult, for every decorator that short-circuits the pipeline without invoking the inner handler (ResultFailure.cs:5-8). It is the one shared home of the lazily built failure delegate that each short-circuiting decorator used to carry as its own private field. - Depends on: ResultFailureFactory (builds the delegate,
ResultFailure.cs:27); Error and Result (MMCA.Common.Shared.Abstractions,ResultFailure.cs:1). - Concept introduced, a per-closed-type lazy cache in a generic static class.
[Rubric §15, Best Practices & Code Quality]assesses how cleanly an awkward generic problem is solved once. Astaticfield on a generic class exists once per closed type, soResultFailure<Result>andResultFailure<Result<OrderDTO>>each hold their own delegate with no dictionary lookup. The remarks (ResultFailure.cs:10-18) give the reason the delegate is built on the first short-circuit for each closed type and never in a static constructor: ResultFailureFactory supports only Result andResult<T>, and an eager initializer would turn an unsupportedTResultinto aTypeInitializationExceptionat resolve time (the pipeline decorates every handler unconditionally) for a handler that never short-circuits. A benign duplicate build under a race produces an equivalent delegate, so no lock is needed, and the happy path never touches the field. - Walkthrough
_create(ResultFailure.cs:21):private static Func<IEnumerable<Error>, TResult>?, null until the first failure for this closed type.From(IEnumerable<Error> errors)(ResultFailure.cs:26-27):(_create ??= ResultFailureFactory.Build<TResult>())(errors), building and caching the delegate on first use, then invoking it.
- Why it's built this way: hoisting the field and its lazy build out of the decorators leaves each short-circuit as a single expression (
ResultFailure<TResult>.From([error])), and keeps the resolve-time rationale written once, on this type, rather than repeated in every decorator's remarks. - Where it's used: eight call sites, each a one-line short-circuit: ViewAsCommandDecorator<TCommand, TResult> (
ViewAsCommandDecorator.cs:31), FeatureGateCommandDecorator<TCommand, TResult> (FeatureGateCommandDecorator.cs:31), FeatureGateQueryDecorator<TQuery, TResult> (FeatureGateQueryDecorator.cs:30), AuthorizationCommandDecorator<TCommand, TResult> (AuthorizationCommandDecorator.cs:40), AuthorizationQueryDecorator<TQuery, TResult> (AuthorizationQueryDecorator.cs:35), ValidatingCommandDecorator<TCommand, TResult> (ValidatingCommandDecorator.cs:53), ValidatingQueryDecorator<TQuery, TResult> (ValidatingQueryDecorator.cs:56), and TimeoutBudget (TimeoutBudget.cs:50), which serves both timeout decorators. - Caveats / not-in-source: the ResultFailureFactory section in this group still describes eight decorators each holding a private
CreateFailure()helper; in current source that helper lives only here.
FeatureGateCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/FeatureGateCommandDecorator.cs:21· Level 5 · class (sealed)
- What it is: the second-outermost standard command decorator, directly inside ViewAsCommandDecorator<TCommand, TResult>. When a command implements IFeatureGated and its feature flag is off, it short-circuits with a
NotFoundfailure before any authorization, logging, caching, validation, budget, or transaction work happens. - Depends on: FeatureFlagGate (the shared check,
FeatureGateCommandDecorator.cs:28); ResultFailure<TResult> (wraps the refusal,:31); IFeatureGated (the opt-in marker the gate tests); ICommandHandler<in TCommand, TResult>;Microsoft.FeatureManagement.IFeatureManager(NuGet,FeatureGateCommandDecorator.cs:1,:23). - Concept introduced, feature-flag gating as a pipeline stage.
[Rubric §12, Performance & Scalability]assesses centralized feature-flag enforcement rather than a flag check duplicated in every handler. Listed second in the outermost-first command list (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:171, with only the view-as guard ahead of it at:170), a disabled feature is rejected before every other standard stage, so no downstream work happens (the class doc says exactly this,FeatureGateCommandDecorator.cs:13-17). Commands that do not implement IFeatureGated pass through on a single type test inside the gate. - Walkthrough:
HandleAsync(FeatureGateCommandDecorator.cs:26) is three lines. It awaitsFeatureFlagGate.EvaluateAsync(command, featureManager)(:28), which returnsnullfor a command that is not gated or whose feature is on, and theFeature.DisabledError otherwise. Anullruns the inner handler (:30); an error returnsResultFailure<TResult>.From([disabled])(:31) without invoking it. The fixed generic message and the reason the flag name stays out of it are documented under FeatureFlagGate; the lazily built failure delegate is documented under ResultFailure<TResult>. - Why it's built this way: putting the gate in a decorator means handlers never inject
IFeatureManager; a command opts in simply by implementing IFeatureGated. Delegating the check to FeatureFlagGate means the command and query twins cannot drift. ReturningNotFoundrather thanForbiddentells the client the operation "does not currently exist" instead of leaking that it exists but is withheld, which is also why the gate deliberately sits outside AuthorizationCommandDecorator<TCommand, TResult>: a feature that is off must answer the same way for every caller rather than leaking which permission guards it (DependencyInjection.cs:118-122). - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:171) around every command handler, directly inside the view-as guard; it engages only for commands implementing IFeatureGated.
ValidatingQueryDecorator<TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidatingQueryDecorator.cs:34· Level 5 · class (sealed, partial)
- What it is: the query-side twin of ValidatingCommandDecorator<TCommand, TResult>. It runs every registered
IValidator<TQuery>before the handler and returns the union of their failures as a Result failure, so a query carrying paging, filter, or sort input rejects a malformed request instead of pushing bad values into the data source (ValidatingQueryDecorator.cs:13-19). - Depends on:
FluentValidation.IValidator<TQuery>(NuGet, injected asIEnumerable<IValidator<TQuery>>,ValidatingQueryDecorator.cs:36); ValidationGate (the shared validation pass,:49); ResultFailure<TResult> (the short-circuit,:56); Error; IQueryHandler<in TQuery, TResult>;Microsoft.Extensions.Logging. - Concept reinforced, and one placement argument that is specific to the read side. The mechanism is ValidatingCommandDecorator<TCommand, TResult>'s, member for member, and both now delegate the validator loop to the same ValidationGate.
[Rubric §24, Forms, Validation & UX Safety]and[Rubric §1, SOLID]. What is new here is where it sits: listed between CachingQueryDecorator<TQuery, TResult> and TimeoutQueryDecorator<TQuery, TResult> in the outermost-first query list (DependencyInjection.cs:187), so the read chain is FeatureGate, Authorization, Logging, Caching, Validating, Timeout, handler (DependencyInjection.cs:104-113). Validation sits inside caching deliberately (ValidatingQueryDecorator.cs:25-27, restated atDependencyInjection.cs:128-131): a cached entry can only exist because the same query already passed validation when the entry was first produced, so re-validating on a cache hit spends work to reach a conclusion already reached. It sits outside the timeout for the mirror of the command-side reason (:27-29): the caller is not charged a slice of its own execution budget for validating its own bad input. - Walkthrough
_validators(ValidatingQueryDecorator.cs:39):[.. validators], materialized once at construction, exactly as on the command side.- Fast path (
ValidatingQueryDecorator.cs:44-47):_validators.Length == 0goes straight to the inner handler, which is the path every production query takes today. - Validation (
ValidatingQueryDecorator.cs:49):ValidationGate.ValidateAsync(query, _validators, cancellationToken)runs every validator sequentially and returns the collected errors ornull(the loop and itsDbContextthread-safety comment live in ValidationGate). - Outcome (
ValidatingQueryDecorator.cs:50-56):errors is nullruns the handler; otherwise it logsLogValidationFailureatDebug(:59-65, instance overload at:67-68) and returnsResultFailure<TResult>.From(errors)(:56).
- Why it's built this way: validation was command-only until the 2026-08-26 revision of ADR-014, which added this decorator so a query with structurally invalid input is rejected on the same Result channel and by the same mechanism as a command, rather than each query handler hand-guarding its own inputs.
[Rubric §15, Best Practices & Code Quality]: the symmetry means a reader who has understood one chain has understood both; with the loop in ValidationGate and the failure in ResultFailure<TResult>, the two files differ only in the generic parameter name, the log message wording, and the placement paragraph. - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:187) around every query handler.AddValidatorsFromAssembly(moduleAssembly)(DependencyInjection.ModuleScanning.cs:82) is what would feed it, since there is no query-side equivalent of the CommandRequestValidator<TCommand, TRequest> auto-wiring. - Caveats / not-in-source: no query validator exists anywhere in the workspace today. A repo-wide search for a FluentValidation validator closed over a query type finds only the framework's own unit tests (
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/ValidatingQueryDecoratorTests.cs), so in every deployed host this decorator constructs an empty_validatorsarray and is a length-check pass-through. It is a live extension point with full test coverage and zero production adopters, which is worth knowing before assuming a query's inputs are checked for you.
ValidatingCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidatingCommandDecorator.cs:31· Level 5 · class (sealed, partial)
- What it is: the decorator that runs FluentValidation against a command before the handler executes, turning validation failures into a Result failure so the handler is never called with invalid input. It runs every registered validator for the command, not just one, and unions their errors. It sits between Caching (outer, when the host opts into caching) and Timeout (inner).
- Depends on:
FluentValidation.IValidator<TCommand>(NuGet, injected asIEnumerable<IValidator<TCommand>>from DI,ValidatingCommandDecorator.cs:33); ValidationGate (the shared validation pass,:46, which applies theToErrorsextension declared atMMCA.Common/Source/Core/MMCA.Common.Application/Extensions/ValidationFailureExtensions.cs:62); ResultFailure<TResult> (the short-circuit,:53); Error; ICommandHandler<in TCommand, TResult>;Microsoft.Extensions.Logging. - Concept introduced, automatic validation as a pipeline stage.
[Rubric §24, Forms, Validation & UX Safety]assesses whether server-side validation is applied consistently rather than hand-called per handler;[Rubric §1, SOLID](SRP) assesses that validation is this decorator's single job and not the handler's. Placing it before the budget and the transaction (stated in the class doc,ValidatingCommandDecorator.cs:24-26, and argued atDependencyInjection.cs:127-128and:134-137) means an invalid command never opens a database transaction and never consumes execution budget. Commands with no registered validator pass straight through, so validation is present-when-registered rather than a hard requirement. - Walkthrough
_validators(ValidatingCommandDecorator.cs:36):[.. validators], the injected enumerable materialized once into an array at construction. Injecting the enumerable rather than the validator itself is what lets a command have none without a DI resolution failure; materializing it once means the DI enumerable is not re-enumerated per execution.- Fast path (
ValidatingCommandDecorator.cs:41-44):_validators.Length == 0passes straight through to the inner handler. - Validation (
ValidatingCommandDecorator.cs:46):ValidationGate.ValidateAsync(command, _validators, cancellationToken). The loop itself lives in ValidationGate (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidationGate.cs:22-47): aList<Error>? errorsallocated only on the first failure (:38), each validator awaited in turn (:32), failures appended viaToErrors(typeof(TRequest).Name)(:39). It is sequential on purpose and the comment says why (ValidationGate.cs:27-29): a validator is free to reach the database through a scoped repository and aDbContextis not thread-safe, so running the set concurrently would trade a correctness guarantee for a saving measured in microseconds. - Outcome (
ValidatingCommandDecorator.cs:47-53):errors is nullruns the inner handler; otherwise it logs and returnsResultFailure<TResult>.From(errors)(:53), so the caller sees every broken rule from every validator in one response. The lazily built failure delegate and its resolve-time remarks now live once in ResultFailure<TResult>. - Logging (
ValidatingCommandDecorator.cs:56-62):partialplus[LoggerMessage]generates the low-allocationLogValidationFailure(logger, commandName, errorCount)atDebug, with a small private instance overload (:64-65) that supplies the logger and the command name so the call site stays one argument.
- Why it's built this way: it removes the "inject
IValidator<T>and callValidateAsyncby hand" boilerplate from every handler; short-circuiting before the budget and transaction stages spares the database work on invalid input; and failing to aResultrather than throwing keeps validation on the same error channel as domain rules. Running every registered validator instead of the first is the 2026-08-31 correction in ADR-014, and the class doc gives the argument (ValidatingCommandDecorator.cs:18-21): a command commonly carries a module-authored validator beside a framework or cross-cutting one, and honoring only the first registration turns the others into dead code whose rules are silently unenforced. - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:175). Every command with a matchingIValidator<TCommand>in DI is validated here. Two registration paths feed it:AddValidatorsFromAssembly(moduleAssembly)picks up every hand-written validator in a module (DependencyInjection.ModuleScanning.cs:82), and the auto-wired CommandRequestValidator<TCommand, TRequest> is added for each command implementing ICommandWithRequest<out TRequest> (DependencyInjection.ModuleScanning.cs:86-100). - Caveats / not-in-source: the auto-wiring uses
TryAddTransient(DependencyInjection.ModuleScanning.cs:99), so it is skipped entirely when anyIValidator<TCommand>is already registered. That is a registration-time interaction, not a runtime one: a module that hand-writes a validator for a request-carrying command gets only the hand-written one, even though the decorator itself would happily run both. There is also no ordering guarantee across validators beyond DI registration order, so error order in the response is a function of registration.
TimeoutBudget
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TimeoutBudget.cs:11· Level 5 · class (static, internal)
- What it is: the execution-budget logic shared by TimeoutCommandDecorator<TCommand, TResult> and TimeoutQueryDecorator<TQuery, TResult>, "so the two cannot drift" (
TimeoutBudget.cs:7-10). Its one member,RunAsync, runs the inner handler under the request's IHasTimeout budget and turns an expired budget into aRequest.TimedOutfailure result instead of an exception. - Depends on: IHasTimeout (the opt-in marker,
TimeoutBudget.cs:35); ResultFailure<TResult> (:50); Error and ErrorType (Error.Unavailable); CqrsMetrics (RecordTimeout,:48); BCLCancellationTokenSourceandSystem.Globalization(:1). - Concept introduced, converting a cancellation into a value on the Result channel.
[Rubric §29, Resilience, Reliability & Business Continuity]assesses bounded failure;[Rubric §9, API & Contract Design]assesses how an outcome is classified for callers. Two decisions here are worth reading closely. First, the classification: an expired budget isErrorType.Unavailablewith the machine-readable codeRequest.TimedOut(TimeoutBudget.cs:50-51); the decorators' class docs give the argument (TimeoutCommandDecorator.cs:13-18): the work (usually a dependency such as the database) did not answer in time, the request was not wrong, so it is HTTP 503 at the edge and retryable later, and the code tells a timeout apart from other outages. Second, whose cancellation it is matters (TimeoutBudget.cs:24-28): a cancellation raised by the caller's token is rethrown unchanged; only the budget's own expiry becomes a failure result.[Rubric §1, SOLID]: factoring the body out of the two decorators leaves each a one-line forwarder, so a fix to the budget lands on both sides at once. - Walkthrough
RunAsync<TRequest, TResult>(TRequest request, string kind, Func<TRequest, CancellationToken, Task<TResult>> next, CancellationToken cancellationToken)(TimeoutBudget.cs:29-33):kindis"command"or"query"and only shapes the message (:20);nextis the inner handler'sHandleAsync, passed as a method group by each decorator.- Opt-out guard (
TimeoutBudget.cs:35-36):request is not IHasTimeout hasTimeout || hasTimeout.Timeout <= TimeSpan.Zerocallsnextwith the caller's token untouched. The non-positive branch is the misconfiguration guard (:25-26, andTimeoutCommandDecorator.cs:25-26): a bad value must not fail every request instantly. - Budget (
TimeoutBudget.cs:38-39):using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)thenbudget.CancelAfter(hasTimeout.Timeout). Linking is what preserves caller cancellation;usingis what disposes the timer. - Execution (
TimeoutBudget.cs:43):nextis invoked withbudget.Token, not the caller's, so everything downstream (on the command side the transaction and the handler's database work) observes the budget. - Catch filter (
TimeoutBudget.cs:45):catch (OperationCanceledException) when (budget.IsCancellationRequested && !cancellationToken.IsCancellationRequested). Both halves are load-bearing: the first confirms the budget fired, the second confirms the caller did not cancel, so caller cancellation falls through the filter and propagates. - Failure (
TimeoutBudget.cs:47-55): recordsCqrsMetrics.RecordTimeout(requestName)(:48) withrequestName = typeof(TRequest).Name(:47), then returnsResultFailure<TResult>.From([Error.Unavailable("Request.TimedOut", ...)])with the messageThe {kind} did not complete within its {seconds}s budget.rendered invariantly to at most three decimal places (:52-54) andsourceset to the request type name (:55).
- Why it's built this way: the two timeout decorators were line-for-line copies apart from the type names and the message wording; collapsing them onto one internal static helper removes that duplication without adding a type to the public surface (the class is
internal,TimeoutBudget.cs:11). Returning a value rather than throwing keeps a timeout on the same error channel as every other expected outcome, so an endpoint maps it without acatch. The pipeline positions of the two callers are ADR-014. - Where it's used: called once each by TimeoutCommandDecorator<TCommand, TResult> (
TimeoutCommandDecorator.cs:39) and TimeoutQueryDecorator<TQuery, TResult> (TimeoutQueryDecorator.cs:39). Internal, so no consuming module calls it directly. - Caveats / not-in-source: cancellation is cooperative, so a handler that ignores its token (a blocking call, a provider that does not honour cancellation) runs to completion regardless; the helper only converts the cancellation it observes on the way out. No production command or query implements IHasTimeout today (see that type's caveat), so in every deployed host this is the opt-out branch.
FeatureGateQueryDecorator<TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/FeatureGateQueryDecorator.cs:20· Level 5 · class (sealed)
- What it is: the query-side twin of FeatureGateCommandDecorator<TCommand, TResult>: the outermost standard query decorator, rejecting a gated query with a
NotFoundfailure when its feature flag is off. - Depends on: FeatureFlagGate (
FeatureGateQueryDecorator.cs:27); ResultFailure<TResult> (:30); IFeatureGated; IQueryHandler<in TQuery, TResult>;Microsoft.FeatureManagement(FeatureGateQueryDecorator.cs:1,:22). - Concept reinforced: an identical pattern to FeatureGateCommandDecorator<TCommand, TResult>, and since both delegate to FeatureFlagGate the two return the same error by construction.
[Rubric §12, Performance & Scalability]. The class doc (FeatureGateQueryDecorator.cs:13-16) says "before logging or caching work", a shorter list than the command side's because the two files were written against their own chains, even though the query chain does now also carry authorization and validation stages. - Walkthrough:
HandleAsync(FeatureGateQueryDecorator.cs:25) awaitsFeatureFlagGate.EvaluateAsync(query, featureManager)(:27); anullruns the inner handler (:29), and theFeature.Disablederror returnsResultFailure<TResult>.From([disabled])(:30) without invoking it. - Where it's used: registered by
AddApplicationDecorators()(DependencyInjection.cs:183) as the outermost decorator on every query handler.
TimeoutCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TimeoutCommandDecorator.cs:34· Level 6 · class (sealed)
- What it is: the decorator that enforces a command's own execution budget. When the command implements IHasTimeout with a positive
Timeout, the inner handler runs under a linked cancellation source that self-cancels after the budget, and the resulting cancellation becomes a failure result withErrorType.Unavailableand the codeRequest.TimedOutrather than escaping as an exception (TimeoutCommandDecorator.cs:7-12). - Depends on: TimeoutBudget (the whole mechanism,
TimeoutCommandDecorator.cs:39); IHasTimeout (the opt-in marker, named in the class doc); ICommandHandler<in TCommand, TResult>. - Concept introduced, converting a cancellation into a value on the Result channel, taught in full under TimeoutBudget, which now holds the code.
[Rubric §29, Resilience, Reliability & Business Continuity]and[Rubric §9, API & Contract Design]. What this file still owns is the argument: the classification (TimeoutCommandDecorator.cs:13-18: an expired budget means a dependency did not answer in time, so it isUnavailable, HTTP 503 at the edge, retryable later, andRequest.TimedOuttells a timeout apart from other outages), the placement (:19-23), and the caller-cancellation and non-positive-budget rules (:24-30). - Walkthrough: the primary constructor takes only the inner handler (
TimeoutCommandDecorator.cs:34-35).HandleAsync(:38-39) is an expression-bodied forwarder,TimeoutBudget.RunAsync(command, "command", inner.HandleAsync, cancellationToken), returning the helper'sTaskwithout its ownasyncstate machine. - Why it's built this way: the placement is argued in the registration doc (
DependencyInjection.cs:134-137), in this file's class doc (TimeoutCommandDecorator.cs:19-23), and in ADR-014's 2026-08-18 revision: the budget sits inside validation and outside the transaction, so it covers the database work that actually hangs, does not charge the caller for validation, and cancels the transaction instead of leaving it open. Delegating to TimeoutBudget keeps the command and query budgets from drifting. - Where it's used: listed by
AddApplicationDecorators()(DependencyInjection.cs:176) as the second-innermost command decorator, directly outside TransactionalCommandDecorator<TCommand, TResult>. - Caveats / not-in-source: no production command implements IHasTimeout today (see that type's caveat), so in every deployed host this decorator is a one-type-test pass-through. Note also what the budget cannot do: cancellation is cooperative, so a handler that ignores its token (a blocking call, a provider that does not honour cancellation) runs to completion regardless, and the decorator only converts the cancellation it observes on the way out.
TimeoutQueryDecorator<TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TimeoutQueryDecorator.cs:34· Level 6 · class (sealed)
- What it is: the query-side twin of TimeoutCommandDecorator<TCommand, TResult>, enforcing a per-query execution budget declared by IHasTimeout and reporting an expired budget as
ErrorType.Unavailablewith the codeRequest.TimedOut(TimeoutQueryDecorator.cs:7-17). - Depends on: TimeoutBudget (
TimeoutQueryDecorator.cs:39); IHasTimeout; IQueryHandler<in TQuery, TResult>. - Concept reinforced: see TimeoutBudget for the classification and the caller-cancellation rule; both timeout decorators forward to it and differ only in the type names and the
"query"versus"command"message word.[Rubric §29, Resilience, Reliability & Business Continuity]and[Rubric §12, Performance & Scalability]. The one substantive difference is position: this is the innermost query decorator (DependencyInjection.cs:188), so a cache hit is served by CachingQueryDecorator<TQuery, TResult> before the budget is even started, and a timed-out execution returns a failure that the caching decorator then refuses to cache (TimeoutQueryDecorator.cs:19-23). - Walkthrough: the primary constructor takes only the inner handler (
TimeoutQueryDecorator.cs:34-35).HandleAsync(:38-39) is the expression-bodied forwarderTimeoutBudget.RunAsync(query, "query", inner.HandleAsync, cancellationToken); the opt-out guard, linked budget, two-part catch filter,CqrsMetrics.RecordTimeoutcall andError.Unavailable("Request.TimedOut", ...)failure all live in TimeoutBudget. - Where it's used: listed last by
AddApplicationDecorators()(DependencyInjection.cs:188) as the innermost query decorator, wrapping the concrete handler directly. Its budget-versus-caller-cancellation split is also reused verbatim inside CachingQueryDecorator<TQuery, TResult>'s populate-lock wait, which cites this type as the precedent (CachingQueryDecorator.cs:172). - Caveats / not-in-source: as with the command twin, no production query implements IHasTimeout today, so this is a pass-through in every deployed host.
TransactionalCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TransactionalCommandDecorator.cs:22· Level 8 · class (sealed)
- What it is: the innermost standard command decorator, the one closest to the concrete handler. It wraps the handler in a database transaction only when the command opts in via ITransactional; every other command passes straight through.
- Depends on: ITransactional (the opt-in marker); IUnitOfWork (supplies
ExecuteInTransactionAsync,TransactionalCommandDecorator.cs:1,:20); ICommandHandler<in TCommand, TResult>. No BCL or NuGet dependency beyondTaskandCancellationToken. - Concept introduced, declarative transaction boundaries via a marker.
[Rubric §2, Design Patterns]assesses whether patterns are chosen deliberately rather than decoratively; this is the Decorator pattern in its plainest form, a type that is anICommandHandlerand holds an innerICommandHandler, so the pipeline composes without any handler knowing it exists.[Rubric §12, Performance & Scalability]assesses whether concerns like transactions are handled once, centrally: no handler in either app callsBeginTransaction.[Rubric §8, Data Architecture]assesses whether transaction boundaries are deliberate: here the boundary is declared on the command type, a domain-adjacent artifact reviewable in a pull request, rather than buried in handler code. The class itself is tiny; nearly all of the behavior lives one layer down in DbContextFactory, reached through UnitOfWork. - Walkthrough
- Primary constructor (
TransactionalCommandDecorator.cs:22-24): takes the innerICommandHandler<TCommand, TResult>and an IUnitOfWork. There is no state and no_fieldcapture; both parameters are used directly in the single method. HandleAsync(TransactionalCommandDecorator.cs:27), opt-out path (:26-27):if (command is not ITransactional) return await inner.HandleAsync(command, cancellationToken). A command that has not opted in pays exactly one type test and never touches the unit of work, which is why the decorator can be registered unconditionally on every command handler in the host.- Transactional path (
TransactionalCommandDecorator.cs:33-35):unitOfWork.ExecuteInTransactionAsync(ct => inner.HandleAsync(command, ct), cancellationToken). The handler call is passed as a delegate rather than awaited inline, which is what lets the layer below own begin, commit, rollback, and (crucially) re-run the delegate under an EF Core execution strategy. Note that the lambda forwards the strategy's ownct, not the captured outer token.
- Primary constructor (
- Why it's built this way: opt-in via a marker means only handlers that mutate multiple aggregates, or save twice against one database, pay for a transaction; everything else keeps the single-
SaveChangesAsyncatomicity EF Core already gives. Because transactions are per physical data source and there is no two-phase commit, cross-source consistency is the outbox's job rather than this decorator's (ADR-006). The composition itself, a Scrutor decorator chain over thin handlers with a load-bearing registration order, is ADR-014. - Where it's used: listed by
AddApplicationDecorators()atMMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:177, the last entry of the command pipeline (:168-178), which is written outermost first.DecorateInExecutionOrderwalks that list from the end and applies each entry withTryDecorateWith(DependencyInjection.cs:403-408), so listed-last means applied-first and therefore innermost at runtime: the transaction opens closest to the handler and inside the timeout budget and cache invalidation. That is what makes "invalidate only after a committed mutation" true (DependencyInjection.cs:132-133) and what lets an expired budget cancel the transaction rather than leave it open (:134-136). - Adoption, verified against source: opt-in is deliberately narrow. Seven production commands implement the marker today:
SendPushNotificationCommandin Common itself (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationCommand.cs:23); four in ADC, LinkUserToSpeakerCommand (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/UseCases/LinkUser/LinkUserToSpeakerCommand.cs:11), UnlinkUserFromSpeakerCommand (.../Speakers/UseCases/UnlinkUser/UnlinkUserFromSpeakerCommand.cs:10), RefreshFromSessionizeCommand (.../Events/UseCases/RefreshFromSessionize/RefreshFromSessionizeCommand.cs:13), and BatchAddSessionQuestionAnswersCommand (.../Sessions/UseCases/BatchAddSessionQuestionAnswers/BatchAddSessionQuestionAnswersCommand.cs:23); and two in Store,UploadProductImageCommand(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Products/UseCases/UploadImage/UploadProductImageCommand.cs:25) andReorderProductImagesCommand(.../Products/UseCases/ReorderImages/ReorderProductImagesCommand.cs:23). Four Store commands carry a doc comment stating they are deliberately not transactional because each performs a single save:CheckOutCommand.cs:9,VerifyPaymentCommand.cs:11,ProcessPaymentWebhookCommand.cs:9, andBulkSetInventoryCommand.cs:11, the last of which is asserted in a test (MMCA.Store/Tests/Modules/Sales/MMCA.Store.Sales.Application.Tests/Inventory/BulkSetInventoryTests.cs:264). The full inventory and the reasoning per command live under ITransactional. - Caveats / not-in-source: four behaviors a reader will attribute to this file actually live in DbContextFactory, and the class doc here (
TransactionalCommandDecorator.cs:11-18, which mentions only exceptions) is narrower than what the code below does. (1) A returned failed Result rolls the transaction back exactly like an exception, atomicity over partial persistence (DbContextFactory.cs:534-538,:563-570). (2) The call is re-entrant: a nestedExecuteInTransactionAsyncjoins the ambient transaction instead of opening a second one, so anITransactionalcommand whose handler also opens a transaction no longer throws from EF (DbContextFactory.cs:529-533,:503-511). (3) The whole delegate runs under an EF execution strategy and may be re-executed on a transient failure, with the change tracker reset between attempts so a retry does not insert duplicates (DbContextFactory.cs:539-556,:526-534). (4) A failure of the commit itself is never retried and surfaces as TransactionCommitAmbiguousException (DbContextFactory.cs:557-566,:536-541). In-process domain event dispatch is deferred until after a successful commit and dropped on rollback (DbContextFactory.cs:664-671), via DomainEventSaveChangesInterceptor.
AuthorizationGate
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/AuthorizationGate.cs:18· Level 9 · class (static, internal)
- What it is: the shared evaluator the two authorization decorators call instead of each holding its own copy of the permission check (
AuthorizationGate.cs:9-12).Evaluateruns the IRequiresPermission capability gate against one request and returns the Error? to short-circuit with, ornullwhen the request may proceed. - Depends on: IRequiresPermission (the opt-in marker it type-tests the request against,
AuthorizationGate.cs:45); ICurrentUserService (Roles,User); IPermissionRegistry (HasPermission,:46);AuthClaimTypes.Permissionvia aHasPermissionClaimextension on the principal (:47); CqrsMetrics (RecordAuthorizationDenied,:49); Error and ErrorType. - Concept introduced, one dual-source capability check shared by both transports and both CQRS sides.
[Rubric §11, Security]assesses where the capability check lives and whether the same request is evaluated the same way regardless of caller. The remarks explain the dual grant source (AuthorizationGate.cs:33-37): the permission check grants on either source, exactly as the HTTP policy handler does, a role the host's registry maps to the permission, or anAuthClaimTypes.Permissionclaim on the principal itself. The claim path is what carries a stored grant across a service boundary, since only the minting host reads the grant table; checking the registry alone would deny in one service what the endpoint policy allows in another.[Rubric §1, SOLID]: the class remarks give the reason for the extraction (AuthorizationGate.cs:13-17): the two decorators differ only in which generic parameter names the request, so one shared evaluator means a rule cannot be enforced on commands but silently missing on queries. - Walkthrough
Evaluate(object? request, ICurrentUserService currentUser, IPermissionRegistry permissionRegistry, string requestTypeName)(AuthorizationGate.cs:39-43): the denial metric is recorded inside, so a caller only has to shape the failure (:27-31).- Permission gate (
AuthorizationGate.cs:45-55):request is IRequiresPermission requiresPermissioncombined with!permissionRegistry.HasPermission(currentUser.Roles, requiresPermission.Permission)and!currentUser.User.HasPermissionClaim(requiresPermission.Permission); only when both grant sources fail does it recordCqrsMetrics.RecordAuthorizationDenied(requestTypeName)(:49) and returnError.Forbidden("Authorization.PermissionDenied", ...)naming the missing permission, withsourceset to the request type name (:51-54). - Pass-through (
AuthorizationGate.cs:57):return nullwhen the caller holds the permission, or when the request does not implement IRequiresPermission at all.
- Why it's built this way: the command and query authorization decorators previously each inlined the permission check; pulling it into this one internal static class keeps the two decorators thin callers rather than two copies of the same branching, and the class remarks name the failure that guards against (
AuthorizationGate.cs:13-17): a rule enforced on commands but not on queries reads as working until someone moves a use case from one to the other. ADR-020 supplies the permission model and registry the gate reads; the pipeline position of its two callers is ADR-014. - Where it's used: called once each by AuthorizationCommandDecorator<TCommand, TResult>
.HandleAsync(AuthorizationCommandDecorator.cs:36) and AuthorizationQueryDecorator<TQuery, TResult>.HandleAsync(AuthorizationQueryDecorator.cs:31). Internal and static, so it is an implementation detail of the two decorators rather than something a consuming module resolves or calls directly. - Caveats / not-in-source: the gate checks a capability only; there is no multi-factor step-up marker evaluated here (the gate's summary reads "Evaluates the capability gate",
AuthorizationGate.cs:20-22). As with the two decorators that call it, no production command or query implements IRequiresPermission today, so the gate is exercised only by the decorators' own test suites: a reachable, covered extension point with zero production adopters.
ViewAsCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ViewAsCommandDecorator.cs:21· Level 9 · class (sealed)
- What it is: the outermost command decorator registered by
AddApplicationDecorators(). While the caller holds a view-as token it refuses every command with aForbiddenfailure, so a staff user viewing the app as another user can read but never write in that user's name; for an ordinary caller it is one claim lookup and a pass-through (ViewAsCommandDecorator.cs:8-17). - Depends on: ICommandHandler<in TCommand, TResult> (the inner handler); ICurrentUserService (
User); ClaimsPrincipalExtensions.IsViewAs, which tests for the AuthClaimTypes.ViewAsActorclaim,act_sub(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:170-171,MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthClaimTypes.cs:122); ResultFailure<TResult> (ViewAsCommandDecorator.cs:31); Error. No BCL or NuGet dependency beyondTaskandCancellationToken. - Concept introduced, a read-only impersonation enforced at the use case as well as at the transport.
[Rubric §11, Security]assesses whether support access to another user's view is constrained so it cannot act in that user's name. The class doc frames this decorator as the second layer (ViewAsCommandDecorator.cs:9-12): the HTTP layer already rejects non-safe methods for a view-as caller (ViewAsGuardMiddleware), and this decorator is the one that also covers a command sent from a GET handler or a hub method, a path a method-based HTTP filter cannot see. - Walkthrough
- Primary constructor (
ViewAsCommandDecorator.cs:21-23): the inner handler andICurrentUserService. No options, no logger, no metric. HandleAsync(ViewAsCommandDecorator.cs:26-34):if (!currentUser.User.IsViewAs())the inner handler runs directly (:28-29); otherwise it returnsResultFailure<TResult>.From([Error.Forbidden("Auth.ViewAsReadOnly", "Viewing as another user is read-only.")])(:31-33) without calling the inner handler. The lazily built failure delegate, and the reason it is not built in a static initializer, live once in ResultFailure<TResult>. The error code is an inline literal here, not an AuthErrorCodes constant.
- Primary constructor (
- Why it's built this way: placement is the argued part. Listed first in the outermost-first command list of
AddApplicationDecorators()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:170, pipeline comment:92), it is applied last byDecorateInExecutionOrderand so runs outermost (DependencyInjection.cs:403-407), so a refused command does no feature-flag lookup, permission check, logging, validation or transaction work (ViewAsCommandDecorator.cs:13-16); the design rationale places feature gating directly inside it on the command side (DependencyInjection.cs:118-122), and FeatureGateCommandDecorator<TCommand, TResult> states the same position from its side (FeatureGateCommandDecorator.cs:14). The read-only view-as model, the token'sact_subclaim, and the HTTP guard it backs up are ADR-137 (point 7 names this decorator); the pipeline itself is ADR-014. - Where it's used: wraps every command handler in any host that calls
AddApplicationDecorators()(DependencyInjection.cs:170); there is no query twin, because a view-as caller is allowed to read. Covered byViewAsCommandDecoratorTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/ViewAsCommandDecoratorTests.cs:19,:33,:45: refuses aResultcommand without calling the inner handler, refuses aResult<int>command, delegates for an ordinary caller), and by the pipeline-order conformance inDecoratorPipelineOrderTestsBaseandApplicationPipelineCompositionTests. - Caveats / not-in-source: "outermost" is relative to
AddApplicationDecorators(). A host that also callsAddApplicationProfiling()registers ProfilingCommandDecorator<TCommand, TResult> afterwards (DependencyInjection.cs:237-239), so the profiler wraps outside this guard and a refused command still shows up in a profile. A refusal records no metric and no log line, unlike an authorization denial (which AuthorizationGate counts). Which hosts actually mint view-as tokens is ADR-137's scope, not something this decorator's source shows.
AuthorizationCommandDecorator<TCommand, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/AuthorizationCommandDecorator.cs:28· Level 10 · class (sealed)
- What it is: the command decorator directly inside the feature gate (third from the outside, after ViewAsCommandDecorator<TCommand, TResult> and FeatureGateCommandDecorator<TCommand, TResult>). When a command implements IRequiresPermission and none of the caller's roles or permission claims grants that permission, it short-circuits with a
Forbiddenfailure before logging, cache invalidation, validation, the timeout budget, or the transaction (AuthorizationCommandDecorator.cs:9-19). - Depends on: AuthorizationGate (
AuthorizationCommandDecorator.cs:36, the shared evaluator that holds the branching); ICurrentUserService and IPermissionRegistry (both forwarded straight intoAuthorizationGate.Evaluaterather than read locally); ResultFailure<TResult> (:40); Error; ICommandHandler<in TCommand, TResult>. - Concept introduced, authorization as a use-case concern rather than a transport concern.
[Rubric §11, Security]assesses where the capability check lives and whether it survives a change of transport. The class doc frames this decorator as defense in depth, not a replacement for the endpoint's[Authorize]policy (AuthorizationCommandDecorator.cs:20-24): moving the check next to the use case is what makes a command reached through gRPC, a scheduled job, or another module get checked the same way it is over HTTP.[Rubric §13, Observability & Operability]assesses the factoring: no handler injects a permission service, and every denial increments a counter (inside AuthorizationGate) so a permission denying far more traffic than expected is visible as a metric rather than as a support ticket. - Walkthrough
- Primary constructor (
AuthorizationCommandDecorator.cs:28-31): the inner handler,ICurrentUserServiceandIPermissionRegistry. No fields. HandleAsync(AuthorizationCommandDecorator.cs:34-41): callsAuthorizationGate.Evaluate(command, currentUser, permissionRegistry, typeof(TCommand).Name)(:36). Anullresult runs the inner handler directly (:37-38); otherwise it returnsResultFailure<TResult>.From([denial])(:40). The decorator itself does not type-test the command or readIPermissionRegistry.HasPermission; the marker check, the claim fallback, and the metric live in AuthorizationGate, and the deferred build of the failure delegate (with the resolve-timeTypeInitializationExceptionit avoids) lives in ResultFailure<TResult>.
- Primary constructor (
- Why it's built this way: the placement is the argued part. It sits directly inside the feature gate and outside logging, cache invalidation, validation and the transaction (
DependencyInjection.cs:123-125, class docAuthorizationCommandDecorator.cs:14-19), so a denied command never starts a transaction, never touches the cache and never runs validation, while a feature that is off is still rejected first, because a disabled feature must not leak the existence of the permission that guards it (DependencyInjection.cs:118-122). ADR-020 supplies the permission model and the registry; the 2026-08-18 revision of ADR-014 inserted this stage into both chains and, in a later revision, extracted the shared AuthorizationGate so the command and query decorators stopped carrying two copies of the same check. - Where it's used: listed by
AddApplicationDecorators()(DependencyInjection.cs:172) third in the outermost-first command list (:168-178), therefore the third wrapper from the outside on every command handler in the host. Because the two authorization decorators are registered unconditionally and take anIPermissionRegistry, the same method first doesservices.TryAddSingleton<IPermissionRegistry, UnconfiguredPermissionRegistry>()(DependencyInjection.cs:154, comment:149-153): a host that declared its grants viaAddAuthorizationPolicies()orAddPermissions(...)keeps its own registry, and a host with no permission model still resolves every handler instead of failing activation. UnconfiguredPermissionRegistry grants nothing (UnconfiguredPermissionRegistry.cs:44-51) and logs one warning the first time a permission is actually checked (:49-60), so the fallback fails closed and says so. Behavior is covered by AuthorizationCommandDecoratorTests and, for the ordering, CommandDecoratorPipelineTests. - Caveats / not-in-source: no production command implements IRequiresPermission today (the only implementers in the workspace are test fakes such as
GuardedCommandatMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/AuthorizationCommandDecoratorTests.cs:89), so this decorator is a pass-through in every deployed host. One behavioral note for whoever adopts it first: because the decorator sits outside LoggingCommandDecorator<TCommand, TResult>, a denial is not recorded in thecqrs.command.durationhistogram and produces no correlated command log line, only the denial counter. The failure travels on the Result channel rather than as an exception, and the framework's transport mappers already translate it: ErrorHttpMapping mapsErrorType.Forbiddento HTTP 403 (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:30) and ResultGrpcExtensions maps it toStatusCode.PermissionDenied(MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:49).
AuthorizationQueryDecorator<TQuery, TResult>
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Decorators·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/AuthorizationQueryDecorator.cs:23· Level 10 · class (sealed)
- What it is: the query-side twin of AuthorizationCommandDecorator<TCommand, TResult>. It is the second-outermost query decorator, denying a query with a
Forbiddenfailure when AuthorizationGate finds the caller lacking its IRequiresPermission permission (AuthorizationQueryDecorator.cs:9-13). - Depends on: AuthorizationGate (
AuthorizationQueryDecorator.cs:31, the shared evaluator); ICurrentUserService and IPermissionRegistry (forwarded into the gate); ResultFailure<TResult> (:35); Error; IQueryHandler<in TQuery, TResult>. - Concept reinforced, plus one property specific to the read side. See AuthorizationCommandDecorator<TCommand, TResult> for the pattern and for
[Rubric §11, Security]. The read-side-specific argument is stated in this file's own doc (AuthorizationQueryDecorator.cs:15-18) and repeated in the registration rationale (DependencyInjection.cs:123-125): the decorator is registered outside CachingQueryDecorator<TQuery, TResult>, so a denied query neither reads nor populates the cache. That ordering is load-bearing rather than tidy: a cache lookup placed ahead of the permission check would serve another caller's cached rows to a principal who is not allowed to run the query at all. - Walkthrough:
HandleAsync(AuthorizationQueryDecorator.cs:29-36) callsAuthorizationGate.Evaluate(query, currentUser, permissionRegistry, typeof(TQuery).Name)(:31); anullresult runs the inner handler (:32-33), otherwiseResultFailure<TResult>.From([denial])returns the gate's failure (:35). As on the command side, the decorator holds no fields and does not type-test the query or callIPermissionRegistry.HasPermissionitself. - Why it's built this way: identical reasoning to the command twin, with the cache-poisoning argument above as the extra constraint that fixes its position relative to caching. Same ADRs: ADR-020 for the permission model, ADR-014 for the pipeline, its 2026-08-18 revision, and the later extraction of AuthorizationGate.
- Where it's used: listed by
AddApplicationDecorators()(DependencyInjection.cs:184) second in the outermost-first query list (:181-189), therefore the second-outermost wrapper on every query handler. Covered by AuthorizationQueryDecoratorTests. - Caveats / not-in-source: as with the command twin, no production query implements IRequiresPermission today (the only implementer is the
GuardedQuerytest fake atMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/AuthorizationQueryDecoratorTests.cs:50), so this is a pass-through in every deployed host. A denial is likewise invisible tocqrs.query.duration, since the decorator sits outside LoggingQueryDecorator<TQuery, TResult>.
EntityCachePrefix
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/EntityCachePrefix.cs:9· Level 0 · class (static)
- What it is: the one place the framework's entity cache prefix is built.
For<TEntity>()andFor(Type)both return"{FullName}:", the key space an aggregate's cached reads live under and the prefix that ICacheInvalidating's generic form and the generic CRUD commands evict on success (EntityCachePrefix.cs:3-8). - Depends on: BCL only (
Type,ArgumentNullException). Its output is consumed by ICacheService'sRemoveByPrefixAsync, whose contract it is shaped to satisfy (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICacheService.cs:101-102). - Concept introduced, one builder for a convention-carrying string.
[Rubric §15, Best Practices & Code Quality]assesses whether a convention lives in one place rather than being retyped at every call site. A cache prefix is exactly that kind of string: it must match the keys the read side wrote and it must end at a:boundary, becauseRemoveByPrefixAsyncthrowsArgumentExceptionfor a non-empty prefix that does not (ICacheService.cs:101). Centralizing the format means every entity-keyed eviction produces the same shape, and the trailing colon stopsProductfrom also evictingProductImage.[Rubric §12, Performance & Scalability]applies too: a correctly bounded prefix evicts only the stale segment. - Walkthrough: line 9 declares
public static class EntityCachePrefix. The generic overload at line 14 is a one-line forward,For(typeof(TEntity)). TheTypeoverload (:19-24) guards withArgumentNullException.ThrowIfNull(entityType)(:21) and returnsentityType.FullName + ":"(:23). - Why it's built this way: ADR-099 gives the generic write-side commands a defaulted, entity-keyed prefix; extracting the format into this helper lets those commands and the entity-keyed marker share it instead of each spelling
typeof(TEntity).FullName + ":". The non-generic overload exists for callers that hold only aType. - Where it's used: the default interface implementation on
ICacheInvalidating<TEntity>(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/ICacheInvalidating.cs:42), and theinit-ableCachePrefixdefaults on DeleteEntityCommand<TEntity, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/DeleteEntityCommand.cs:22) and UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/UpdateEntityCommand.cs:65). Exercised byCacheInvalidatingTestsinMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/UseCases/Markers/.
IFeatureGated
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/IFeatureGated.cs:10· Level 0 · interface
- What it is: an opt-in interface that puts both commands and queries behind a Microsoft.FeatureManagement flag. When the named feature is disabled, the gate short-circuits and returns a failure result without calling the handler.
- Depends on: nothing first-party at the interface level. Enforcement lives in FeatureGateCommandDecorator<TCommand, TResult> and FeatureGateQueryDecorator<TQuery, TResult>, which depend on
IFeatureManager(Microsoft.FeatureManagement) and callIsEnabledAsync(FeatureName)(IFeatureGated.cs:5-8). - Concept introduced, feature flags as a cross-cutting pipeline concern.
[Rubric §12, Performance & Scalability]assesses whether concerns like flags, logging, and caching are factored out of business logic; the gate sits at the handler boundary as the outermost query decorator and, on the command side, directly inside the view-as guard that refuses every command for a read-only view-as caller (MMCA.Common.Application/DependencyInjection.cs:92-93,:106,:118-120; see ICommandHandler<in TCommand, TResult> and IQueryHandler<in TQuery, TResult>), so no caller needs a flag check and the handler has no flag knowledge. As with ITransactional, the interface goes on the command or query record, not on the handler: both decorators delegate to the shared internalFeatureFlagGate, which testsrequest is not IFeatureGatedand passes everything else straight through (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/FeatureFlagGate.cs:23-26, called atFeatureGateCommandDecorator.cs:28and.../FeatureGateQueryDecorator.cs:27). Its position relative to IRequiresPermission is deliberate and argued in the registration doc (MMCA.Common.Application/DependencyInjection.cs:121-122): the flag is checked before the permission, so a feature that is off answers the same way for every caller rather than leaking which permission guards it. - Walkthrough: line 10 declares
public interface IFeatureGated; line 16 declaresstring FeatureName { get; }, which must match a key in theFeatureManagementconfiguration section (documented on lines 12-15). The shared check is three branches long: no marker means pass through (FeatureFlagGate.cs:23), an enabled flag means pass through (:24-26), and a disabled flag returnsError.NotFoundErrorwith the codeFeature.Disabledand a generic message that keeps the internal flag name out of it (:29-34), which the decorator wraps as a failure result (FeatureGateCommandDecorator.cs:29-31). Answering not found rather than forbidden is the same non-disclosure choice as the ordering: a disabled feature looks like a route that does not exist. - Why it's built this way: putting the gate in the pipeline applies it uniformly to every gated command and query with zero per-handler boilerplate, and one interface serves both sides because a feature-gate decorator is registered against both handler interfaces (
MMCA.Common.Application/DependencyInjection.cs:171on the command list and:183on the query list). - Where it's used: sparingly and deliberately, on the three operations that genuinely need a runtime kill switch. Verified by source search, the production implementers are
MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/UseCases/VerifyPayment/VerifyPaymentCommand.cs:19, which combines it with IHasTimeout;MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/RefreshFromSessionize/RefreshFromSessionizeCommand.cs:14(RefreshFromSessionizeCommand), which implements it alone and is documented as deliberately not ITransactional (:8); andMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/DecisionSupport/ScoreEventSessions/ScoreEventSessionsInternalCommand.cs:37, which combines it with IRequiresPermission and IHasTimeout. Feature-name constants live in per-module*Featuresclasses to avoid magic strings (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Shared/SalesFeatures.cs:6,MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Shared/CatalogFeatures.cs:6, ConferenceFeatures, EngagementFeatures), and each doc comment notes that the same constant serves both the[FeatureGate]attribute on a controller and this interface on a command. Feature state is read from configuration at runtime.
IHasTimeout
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/IHasTimeout.cs:14· Level 0 · interface
- What it is: an opt-in interface by which a command or query declares its own execution budget as a
TimeSpan. TimeoutCommandDecorator<TCommand, TResult> and TimeoutQueryDecorator<TQuery, TResult> enforce it by linking a cancellation source to the caller's token, cancelling it after the budget, and converting the resulting cancellation into a failure result instead of letting it surface as an exception. - Depends on: BCL only (
TimeSpan). Enforced by the two timeout decorators; the expiry is counted by CqrsMetrics throughRecordTimeout(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CqrsMetrics.cs:86, instrumentcqrs.timeout.countat:60). Same presence-as-signal shape as IFeatureGated, ICacheInvalidating and IRequiresPermission, except that this marker carries data rather than only a name. - Concept introduced, a per-request execution budget owned by the request type.
[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether a slow or wedged dependency can consume a caller indefinitely; a budget bounds the blast radius of one hung handler without a global timeout that would have to be tuned for the slowest operation in the system.[Rubric §12, Performance & Scalability]assesses load-shedding behavior: a request that has already blown its budget is work nobody is waiting for. Two properties make the contract safe to adopt. First, the budget is aTimeSpan, not a seconds int, so a caller cannot silently mean milliseconds. Second, a non-positive value is "no budget" (IHasTimeout.cs:16-21), which is the guard against a misconfigured or defaulted value failing every request instantly; the decorators implement it ashasTimeout.Timeout <= TimeSpan.Zeroin the same test that checks the interface (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TimeoutBudget.cs:35, the internal helper both decorators delegate to atTimeoutCommandDecorator.cs:39andTimeoutQueryDecorator.cs:39). Opting in is per request type: anything that does not implement the interface passes through the decorator untouched and keeps the caller's token unchanged (IHasTimeout.cs:9-12). - Walkthrough: line 14 declares
public interface IHasTimeout; line 21 declares its only member,TimeSpan Timeout { get; }. The doc comment on lines 3-13 names both decorators and states the conversion contract, which is the part a reader has to know before adding the interface to a command. Both decorators delegate to the shared internalTimeoutBudget.RunAsync(TimeoutCommandDecorator.cs:39), where the mechanism is a few lines: a linked source over the caller's token (TimeoutBudget.cs:38),CancelAfter(hasTimeout.Timeout)(:39), the inner call onbudget.Token(:43), and an exception filter that only catches the cancellation this budget caused,when (budget.IsCancellationRequested && !cancellationToken.IsCancellationRequested)(:45), so a caller who genuinely walked away still sees a cancellation rather than a fabricated timeout. The failure it builds, afterCqrsMetrics.RecordTimeout(:48), isError.Unavailablewith the codeRequest.TimedOutand a message quoting the budget in seconds (:50-55), so an expired budget arrives at the caller on the same Result channel as a validation failure. - Why it's built this way: ADR-014, revised 2026-08-18, records both the marker and its placement in the two chains. Putting the value on the request type rather than in configuration keeps the budget next to the operation it bounds and reviewable in the same pull request, exactly as IQueryCacheable keeps
CacheDurationon the query. - Where it's used: read by the two timeout decorators only.
- Caveats / not-in-source: verified by source search, the production adopters are commands that wait on a slow external dependency or do heavy I/O. In MMCA.Store:
MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/UseCases/VerifyPayment/VerifyPaymentCommand.cs:19(combined with IFeatureGated) andMMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/UseCases/CreateCheckoutSession/CreateCheckoutSessionCommand.cs:20, whose doc comment explains why its budget is deliberately longer thanVerifyPaymentCommand's and stays inside the shared 90-second request timeout (:22-30). In MMCA.ADC:MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/UploadFile/UploadSessionAssetCommand.cs:34,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/DecisionSupport/ScoreEventSessions/ScoreEventSessionsInternalCommand.cs:37(combined with IRequiresPermission and IFeatureGated),MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/UseCases/ProcessRosterImport/ProcessTicketRosterImportInternalCommand.cs:22andMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarCommand.cs:12. All of them are commands, soTimeoutQueryDecoratorremains a pass-through for every production query; the framework's test doubles inMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/TimeoutCommandDecoratorTests.csandTimeoutQueryDecoratorTests.csexercise both decorators directly.
IQueryCacheable
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/IQueryCacheable.cs:8· Level 0 · interface
- What it is: the query-side opt-in for caching. A query implements this to declare a
CacheKey(the exact lookup key for this query's result) and aCacheDuration(per-query TTL); CachingQueryDecorator<TQuery, TResult> checks the cache on the way in and stores the result on a miss. - Depends on: nothing first-party. Query-side companion to ICacheInvalidating; implemented through ICacheService and tenant-scoped through ITenantContext exactly as the write side is. For a caller-scoped result it composes with
IUserScopedRequest(MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserScopedRequest.cs) and can be opted back out of caller-scoping with ISharedQueryCache. - Concept introduced, per-query cache keys and staleness budgets.
[Rubric §12, Performance & Scalability].CacheKeymust encode every query parameter that affects the result, and the XML doc gives the shape ("Catalog:Products:page=1&size=10",IQueryCacheable.cs:10-22); omit a parameter and the cache answers one query shape with another's result.CacheDurationgives per-query TTL control so a hot, stable list can cache longer than volatile data, and putting it on the interface rather than in configuration keeps each query the owner of its own staleness budget. This is also[Rubric §11, Security]: the doc comment now calls out the caller itself as a parameter of the key (IQueryCacheable.cs:14-21) whenever the result is that caller's own data, because the caller is the one dimension that is not visible in a hand-writtenCacheKey.CachingQueryDecorator<TQuery, TResult>folds the caller in automatically for a query that also implementsIUserScopedRequest; a caller-scoped query that does not carry the target user on the request must either add that interface or put the caller into the key by hand, or the first caller's rows are served to the second for the wholeCacheDuration. A query that opts out through ISharedQueryCache is asserting its result really is the same for every caller. - Walkthrough: line 8 declares
public interface IQueryCacheable; the doc comment onCacheKey(:10-22) carries the caller-as-parameter guidance above; line 23 declaresstring CacheKey { get; }, computed from the query's own properties; line 28 declaresTimeSpan CacheDuration { get; }(IQueryCacheable.cs:8-29). - Why it's built this way: opt-in means only queries that genuinely benefit (frequently called, expensive, not user-specific) pay the serialization and staleness cost. A query that does not implement it hits the decorator's early return and goes straight to the handler.
- Where it's used: by no production query in Common, ADC or Store today. ADC's one hot public read, GetNowNextQuery, opts out on purpose: its endpoints serve it through the 60-second Redis-backed
NowNextCacheoutput-cache policy, evicted by tag across replicas, and a second per-query cache would only stack a second TTL on the same payload (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/NowNext/GetNowNextQuery.cs:10-12). The framework's ownExportUserDataHandlerBasedoes not implement it either (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:55-56). The adopter is the Helpdesk reference app (GetTicketByIdQuery,MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/Tickets/UseCases/GetById/GetTicketByIdQuery.cs:23), and the unit tests in CachingQueryDecoratorTests exercise the decorator directly, alongsideCallerScopedQueryCacheTestsfor theIUserScopedRequestfolding path. - Caveats / not-in-source: the read-cache mechanism is fully functional and unit-tested, but no production query adopts it, so do not assume an existing query is cached through this path. Production read-side caching is done a layer up, at HTTP, through ASP.NET Core OutputCache policies on the Conference read controllers. The caller-as-parameter path described above is covered by unit tests only.
IRequiresPermission
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/IRequiresPermission.cs:34· Level 0 · interface
- What it is: an opt-in interface by which a command or query names the fine-grained permission its caller must hold. AuthorizationCommandDecorator<TCommand, TResult> and AuthorizationQueryDecorator<TQuery, TResult> resolve the caller's roles, ask the permission registry whether any of them grants it, and short-circuit with a
Forbiddenfailure when none does. - Depends on: nothing first-party at the interface level. Enforcement pulls in ICurrentUserService (the caller's roles) and IPermissionRegistry (the role-to-permission map), and the failure is an Error of ErrorType
Forbidden. - Concept introduced, capability checks moved from the transport to the use case.
[Rubric §11, Security]assesses whether authorization is enforced where the operation lives rather than only where it happens to be exposed; the interface's own doc makes the claim precise (IRequiresPermission.cs:18-22): opting in is per request type, so a command or query that does not implement it passes through untouched and endpoint-level[Authorize]policies remain the only gate for everything that has not opted in. That is defense in depth, not a replacement (AuthorizationCommandDecorator.cs:21-24): the value of moving the check inward is that a command reached through a new transport (gRPC, a scheduled job, another module) is checked exactly the way it is over HTTP.[Rubric §1, SOLID]: adding a permission requirement to a use case is a one-interface change with no decorator, endpoint or registry code touched. The fail-closed default is stated on the member itself (IRequiresPermission.cs:36-40): a permission string the host's registry does not know about is granted by no role and therefore denies every caller, so a typo locks the operation rather than opening it. The same fail-closed posture is why the decorators are registered unconditionally over aTryAddSingletonfallback registry, so a host with no permission model still resolves every handler (MMCA.Common.Application/DependencyInjection.cs:149-154). - Walkthrough: line 34 declares
public interface IRequiresPermission; line 41 declares its only member,string Permission { get; }, documented with the dotted-capability convention ("catalog.products.write",:37). Both decorators delegate to the shared internalAuthorizationGate.Evaluate(AuthorizationCommandDecorator.cs:36,AuthorizationQueryDecorator.cs:31) and pass through when it returns no denial (AuthorizationCommandDecorator.cs:37-38), otherwise wrapping the denial as a failure result (:40). The gate denies only when the request implements the interface,permissionRegistry.HasPermission(currentUser.Roles, requiresPermission.Permission)is false, and the principal carries nopermissionclaim with that value (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/AuthorizationGate.cs:45-47), mirroring the HTTP policy handler so a grant minted by another host is honored in the pipeline too (IRequiresPermission.cs:10-17). A denial is counted byCqrsMetrics.RecordAuthorizationDenied(AuthorizationGate.cs:49) and returned asError.Forbiddenwith the codeAuthorization.PermissionDenied(:51-54). The remarks (IRequiresPermission.cs:24-33) add the rule for deferred work: the gate evaluates the principal restored from the scheduling request, so a command that can be scheduled without an operator behind it must not carry the marker.HasPermissionreturns true if any supplied role grants the permission (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/IPermissionRegistry.cs:29, implemented as a short-circuiting loop over a role-keyed dictionary atMMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistry.cs:67-83). - Why it's built this way: ADR-020 established permissions (capabilities) as the authorization currency and the registry as the single place that knows which roles confer which permissions; ADR-014, revised 2026-08-18, is what put the check into the CQRS pipeline and fixed its position: directly inside the feature gate and outside logging and caching, so a denied request neither reads nor populates the cache (
MMCA.Common.Application/DependencyInjection.cs:123-125). That ordering is load-bearing: a cache lookup ahead of the permission check would serve another caller's cached rows to a principal not allowed to run the query at all. - Where it's used: read by the two authorization decorators only.
- Caveats / not-in-source: verified by source search, the production adopters are deferred internal commands that re-check the capability their trigger endpoint required, which is exactly the "new transport" case above. In MMCA.ADC:
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/DecisionSupport/ScoreEventSessions/ScoreEventSessionsInternalCommand.cs:37, requiringConferencePermissions.SessionSelectionManage(:55). In MMCA.Store:MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Application/Orders/InternalCommands/SendOrderShippedEmailInternalCommand.cs:26andMMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Products/InternalCommands/PublishProductVariantChangedInternalCommand.cs:29. Each doc comment explains why the gate is safe on a deferred command: the row carries the scheduling principal, whichInternalCommandProcessorrestores before the handler runs (ScoreEventSessionsInternalCommand.cs:49-54,SendOrderShippedEmailInternalCommand.cs:28-32,PublishProductVariantChangedInternalCommand.cs:31-35). Other internal commands decline it on purpose and say so (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/UseCases/ProcessRosterImport/ProcessTicketRosterImportInternalCommand.cs:13,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/DeleteSessionAssetBlob/DeleteSessionAssetBlobInternalCommand.cs:17). No production query implements it, soAuthorizationQueryDecoratoris a pass-through for every production query, and HTTP requests in both deployed apps are still authorized at the endpoint with[Authorize]/[HasPermission]attributes. The framework's test doubles inMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/AuthorizationCommandDecoratorTests.csandAuthorizationQueryDecoratorTests.csexercise both decorators directly.
ISharedQueryCache
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/ISharedQueryCache.cs:21· Level 0 · interface (marker)
- What it is: the opt-out from the caller-scoped cache key. It declares that a query addressed at a single user nevertheless produces a result every caller may be served, so its cache entry is shared rather than scoped to that user (
ISharedQueryCache.cs:4-5). - Depends on: nothing (BCL only) at the interface level. Query-side companion to IQueryCacheable and read by CachingQueryDecorator<TQuery, TResult>, which builds the caller-scoped key via UserCacheKey when this marker is absent.
- Concept introduced, a safe default for caller-scoped caching, with an explicit, documented opt-out.
[Rubric §11, Security]assesses whether a shared-infrastructure concern like caching can leak one caller's data to another; the default direction here is the safe one. By default, a query that implements bothIUserScopedRequestand IQueryCacheable has its cache key prefixed with the target user id, because the commonest reason to address a query at one user is that its result is that user's own data, and a missing prefix serves one caller's personal data to another while a needless prefix only costs an extra cache entry (ISharedQueryCache.cs:9-13).[Rubric §2, Design Patterns]: it is the same marker-interface opt-in shape as ITransactional and ICacheInvalidating, used here to widen rather than to activate a behavior, so the code identifier is where the risk decision is visible in review. Add this marker only for a query whose result genuinely does not vary by caller (a public profile card, a published-count badge); the doc comment calls the choice deliberate and asks the implementer to state the reason on the query type (:16-19). - Walkthrough: line 21 declares
public interface ISharedQueryCache;, a zero-member marker. The doc comment carries the whole contract: the default caller-scoping behavior (:9-13) and the narrow, justified opt-out (:16-19). It references SEC-Common-37 (:9), the same security item cited on IQueryCacheable'sCacheKeydoc comment, tying the two together as one fix. - Why it's built this way: making caller-scoping the default and this marker the exception means a query author has to actively assert "this is safe to share" rather than actively remember to scope it; a forgotten scope fails safe (an extra cache entry) rather than fails open (a leaked entry).
- Where it's used: read by CachingQueryDecorator<TQuery, TResult> through UserCacheKey. Exercised by the framework's own
CallerScopedQueryCacheTests; no production query inMMCA.ADC/SourceorMMCA.Store/Sourceimplements it today. - Caveats / not-in-source: like IQueryCacheable itself, the caller-scoping and this opt-out are unit-tested but have no production adopter, since no production query implements
IQueryCacheableat all.
ITransactional
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/ITransactional.cs:6· Level 0 · interface (marker)
- What it is: a C# empty-body interface (
public interface ITransactional;) that a command implements to opt in to database-transaction wrapping by TransactionalCommandDecorator<TCommand, TResult>. - Depends on: nothing (BCL only).
- Concept introduced, marker interfaces as opt-in decorator switches.
[Rubric §2, Design Patterns]assesses the deliberate, idiomatic use of patterns; a marker interface carries no members, so its mere presence on a type is the signal. The decorator's whole dispatch isif (command is not ITransactional)followed by a pass-through (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TransactionalCommandDecorator.cs:29-31). Read that line carefully: the marker goes on the command record, not on the handler class, which is the same convention IFeatureGated, ICacheInvalidating, IHasTimeout and IRequiresPermission follow. This is also[Rubric §1, SOLID](open for extension): the pipeline gains new transactional commands with no change to any existing decorator. The semicolon-body syntax (interface ITransactional;, line 6) is the idiomatic zero-member declaration and is used consistently across the framework's markers, including ICommand<TResult> and IQuery<TResult>. - Walkthrough: the entire file body is
public interface ITransactional;at line 6, under the doc comment on lines 3-5. No members; the type is the message. - Why it's built this way: keeping transaction scope opt-in spares single-statement commands the cost of an explicit begin and commit around a save that is already atomic. Commands that mutate multiple aggregates, or that save twice against one database, opt in. The behavior that comes with opting in is documented in ADR-014 and
MMCA.Common/CLAUDE.md, and is worth knowing before you add the marker: exceptions and business failures (Result.Failure) both roll back, and in-process domain event dispatch is deferred until after a successful commit, so handlers never act on state that could still roll back. - Where it's used: sparingly, and the restraint is deliberate. Verified by source search, 10 implementers in
MMCA.ADC/Source(among themBatchAddSessionQuestionAnswersCommand.cs:23,LinkUserToSpeakerCommand.cs:11andUnlinkUserFromSpeakerCommand.cs:10, plusBatchAddEventQuestionAnswersCommand,DeleteSessionAssetCommand, three Engagement ticket-roster commands and the IdentityDeleteUserCommandandRedeemSignInLinkCommand) and 4 inMMCA.Store/Source(UploadProductImageCommand.cs:25andReorderProductImagesCommand.cs:23, both of which write in two saves against the same database and document why on lines 8 and 10 respectively, plusAddVariantCommand.cs:24and the IdentityMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/DeleteUser/DeleteUserCommand.cs:24).RefreshFromSessionizeCommandis not one of them: its doc comment marks it "Deliberately NOTITransactional" (RefreshFromSessionizeCommand.cs:8). Several Store commands a reader would expect to see here carry a doc comment saying the opposite, each explicitly annotated "Deliberately NOTITransactional":BulkSetInventoryCommand.cs:9,VerifyPaymentCommand.cs:10andProcessPaymentWebhookCommand.cs:6, because their handlers reach the database in a single save that is already atomic, andCheckOutCommand.cs:8, because its handler opens its own transaction around the write phase only, after the cross-service pre-flight reads (:8-13). Inspected at execution time by TransactionalCommandDecorator<TCommand, TResult>, the innermost command decorator, so it sits closest to the handler (see the registration note under ICommandHandler<in TCommand, TResult>).
ICacheInvalidating
MMCA.Common.Application ·
MMCA.Common.Application.UseCases.Markers·MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/ICacheInvalidating.cs:8· Level 1 · interface (plus its entity-keyed generic sibling in the same file)
- What it is: an opt-in interface for commands that should evict cached entries after a successful mutation. Implementing it exposes a
CachePrefixstring; CachingCommandDecorator<TCommand, TResult> callsICacheService.RemoveByPrefixAsyncwith that prefix once the inner handler returns a non-failure result. The same file declaresICacheInvalidating<TEntity> : ICacheInvalidating(ICacheInvalidating.cs:39), the entity-keyed form: a command names the aggregate it makes stale and the framework supplies the prefix. - Depends on: EntityCachePrefix, which the generic form calls for its default prefix (
ICacheInvalidating.cs:42); that dependency is why the type sits at Level 1. Works in concert with ICacheService (the eviction mechanism), is tenant-scoped through ITenantContext, and shares the opt-in-by-implementing pattern with ITransactional. - Concept introduced, prefix-based cache invalidation as an opt-in pipeline concern.
[Rubric §12, Performance & Scalability]assesses caching strategy and how stale reads are avoided; prefix-scoped eviction keeps read caches coherent after writes without the command site knowing individual cache keys. Naming the prefix (for example the aggregate's full type name plus:) scopes eviction to only the affected segment. This is also[Rubric §2, Design Patterns]: Decorator plus a presence-as-signal interface, the same shape ITransactional introduces. Note where the interface sits: it is implemented by the command record, not by the handler, because the decorator's type check iscommand is not ICacheInvalidating cacheInvalidating(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingCommandDecorator.cs:98). - Walkthrough: line 8 declares
public interface ICacheInvalidating; line 22 declares its only member,string CachePrefix { get; }. Its doc comment states the prefix contract (:10-21): the value ends at a:boundary ("Catalog:Products:", or the framework default"{typeof(TEntity).FullName}:"), a prefix without the trailing colon is rejected byRemoveByPrefixAsyncwith anArgumentException, and an empty or whitespace value is the opt-out. The genericICacheInvalidating<TEntity>(:39) has no members of its own: it supplies the non-genericCachePrefixas an explicit default interface implementation,string ICacheInvalidating.CachePrefix => EntityCachePrefix.For<TEntity>();(:42), so an entity-keyed command writes no prefix at all. Its remarks (:34-38) record the escape hatch: a command that declares its own publicCachePrefixstill compiles and its member wins, but the shared fitness rule flags it, because a deliberately custom prefix belongs on the non-generic marker and in that rule's allow-list. Four behaviors of the consuming decorator are worth carrying here because they are the contract in practice. (1) Empty means opt out. The guard is split across two methods:HandleAsynccalls the privateInvalidateAsynconly when!IsFailure(result)(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingCommandDecorator.cs:82), andInvalidateAsyncreturns early whencommand is not ICacheInvalidating cacheInvalidatingorstring.IsNullOrWhiteSpace(cacheInvalidating.CachePrefix)holds (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingCommandDecorator.cs:98-102); the comment above that check (:96-97) says why the blank-prefix half is load-bearing:RemoveByPrefixAsync("")would evict the entire cache. The decorator reads only the non-generic member, so both forms dispatch through the same type test. (2) Tenant scoping is applied for you. The prefix is run throughTenantCacheKey.Scope(tenantContext, ...)(CachingCommandDecorator.cs:106, helper atMMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TenantCacheKey.cs:37), so a resolved tenant evicts only its own keyspace. (3) A malformed prefix is a logged bug, not a failed command. AnArgumentExceptionfrom the first eviction is caught separately (CachingCommandDecorator.cs:115-122), logged at Error level as a misconfigured command (:167-174), andInvalidateAsyncreturns with no delayed retry, since the retry would fail identically (:117-121). (4) Otherwise eviction happens twice. The firstRemoveByPrefixAsyncruns withCancellationToken.Noneso cleanup outlives a caller that walked away (:110-113), and a delayed second eviction is scheduled at:136and performed byReInvalidateAfterDelayAsync(:143-156) afterReInvalidationDelay, five seconds (:55), which removes an entry that an in-flight read repopulated with pre-write state. Any other failure in either eviction is caught and logged at Warning, never surfaced to a command that already committed (:123-128,:150-155, message at:158-165), and the follow-up is scheduled even when the first eviction failed so a transient fault gets its retry (:130-136). - Why it's built this way: decoupling what to invalidate (the command's concern, via
CachePrefixor simply the entity type) from how to invalidate (the decorator plusICacheService) keeps handlers free of cache-infrastructure knowledge and makes invalidation testable in isolation. The generic form goes further: naming the aggregate instead of a string removes the chance of a hand-typed prefix that drifts from the keys the read side wrote, which is why the shared ruleCacheInvalidatingCommandsUseEntityKeyedMarker(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Cqrs/ArchitectureRules.CacheInvalidation.cs:37, exposed throughCacheInvalidationConventionTestsBase) requires every concrete implementer in the mapped Application assemblies to useICacheInvalidating<TEntity>and declare no prefix of its own, outside the allow-list (:15-27). A businessResult.Failurestill returns through the pipeline but skips invalidation, because of the!IsFailure(result)check (CachingCommandDecorator.cs:82, helper at:180-181): a failure persisted nothing. A handler that throws is the opposite case: the decorator evicts anyway and then rethrows unchanged (:71-77), because a post-save hook on a non-ITransactionalcommand can throw after the write committed, and after a rollback the eviction only costs a cache miss (:73-75). - Where it's used: broadly adopted on the write side. Verified by source search, 42 files under
MMCA.ADC/Sourcereference it (Conference category, event, session, speaker, partner, question, activity and sponsor mutations, plus Identity user mutations) and 38 underMMCA.Store/Source(catalog, review, sales, cart, inventory and identity mutations, plus one controller). The framework's own DeleteEntityCommand<TEntity, TIdentifierType> and UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> implement the non-generic form with aninit-able prefix defaulted to EntityCachePrefix (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/DeleteEntityCommand.cs:13,22,.../UpdateEntityCommand.cs:52,65). Consumed exclusively by CachingCommandDecorator<TCommand, TResult>.
INavigationPopulatorCoverage
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationPopulatorCoverage.cs:13· Level 2 · interface
- What it is: a one-member capability interface a navigation populator implements to declare which navigations it actually loads.
bool Handles(NavigationPropertyInfo navigation)(INavigationPopulatorCoverage.cs:18) answers whether the populator loads a navigation that the data source cannot include, so the host-start check can prove every cross-data-source navigation has a loader (:3-6). - Depends on: NavigationPropertyInfo, the navigation descriptor it is asked about, which is why it sits at Level 2. It is a companion to INavigationPopulator<in TEntity>, not a sub-interface of it: a populator implements both side by side.
- Concept introduced, a declared capability that turns a silent runtime gap into a startup failure.
[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether a misconfiguration fails loudly and early rather than degrading quietly. A navigation EF Core cannot include (the two entities live in different databases, on Cosmos DB, or the target is not mapped in this host) is loaded only by the entity's populator; without a loader every read that requests it returns it empty, and nothing errors. This interface letsNavigationPopulatorStartupValidatorask each registered populator, at host start, whether it covers every such navigation, and refuse to start when one is uncovered (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:48-58).[Rubric §2, Design Patterns]: it is a role interface kept separate from the populating contract, so the check is optional per implementation rather than a member every populator must carry. The trust rule is explicit (INavigationPopulatorCoverage.cs:7-12): a hand-written populator that does not implement it is assumed to handle every navigation of its entity, because nothing about its code can be inspected. - Walkthrough: line 13 declares
public interface INavigationPopulatorCoverage; line 18 declares its only member,Handles, whose argument is documented as "a navigation the data source cannot include" (:16). The validator consumes it in a three-arm switch (NavigationPopulatorStartupValidator.cs:108-113): no registered populator means unhandled, a populator implementing this interface answers throughcoverage.Handles(navigation)(:111), and any other populator is trusted (:112). The two framework implementations bracket the range. NullNavigationPopulator<TEntity>, the open-generic default, handles nothing (Handles => false,MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NullNavigationPopulator.cs:24), so an entity with a cross-source navigation and no real populator fails the check. DeclarativeNavigationPopulator<TEntity> answers from its descriptors (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/DeclarativeNavigationPopulator.cs:66-74): a descriptor handles a navigation when the property names match ordinally and itsRequiresChildrenflag agrees with whether the navigation is a child collection (:70-73). The same method also guards the request path: after loading,PopulateAsynclogs a warning for every requested unsupported navigationHandlesrejects (:54-57), covering a host whose hosted services did not run. - Why it's built this way: ADR-002 makes populators the only path for cross-source reads, and the validator's failure message points back to it, naming each uncovered navigation as
{Entity}.{Navigation} -> {TargetEntity}and telling the host to register aDeclarativeNavigationPopulator<TEntity>with a descriptor for each (NavigationPopulatorStartupValidator.cs:51-57, format at:93). Declaring coverage on the populator, rather than in a separate registry, keeps the answer next to the descriptors that decide it. The check is cheap when there is nothing to prove: a host whose navigations all share one relational database resolves no populator at all (:26-28, lazy scope at:85-87). - Where it's used: implemented by
DeclarativeNavigationPopulator<TEntity>(DeclarativeNavigationPopulator.cs:26) andNullNavigationPopulator<TEntity>(NullNavigationPopulator.cs:13); read by the internalNavigationPopulatorStartupValidator(NavigationPopulatorStartupValidator.cs:111), whichAddInfrastructureregisters as anIHostedServicethroughTryAddEnumerable(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:270). Exercised byNavigationPopulatorStartupValidatorTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Navigation/NavigationPopulatorStartupValidatorTests.cs:33).
⬅ Domain & Integration Events + Outbox Dual-Dispatch • Index • Validation ➡