Onboarding guide
14. Module System, Composition & Configuration
What this chapter covers. This is the wiring layer, the code that turns a pile of layered
assemblies into a running host. It answers three questions a new host author asks: how does the
process discover and assemble its modules?, in what order does DI get built so the decorators wrap
the right handlers?, and where do the dozens of appsettings.json knobs land as typed objects?
The cast is small but load-bearing: the IModule contract and its
IModuleSeeder sidekick; the ModuleLoader that discovers and
Kahn-sorts them; the two extension(IServiceCollection) DependencyInjection
composition roots (Application and Infrastructure) plus the
MmcaApplicationPipelineBuilder and the
DecoratorPipelineSeal marker that together make the ordering rule
enforceable instead of merely documented, the QueryCachingOptIn marker that
splices the caching pair in, and the framework's own scan-and-decorate helper
ServiceCollectionDecoration with its
ScanRegistration mode and private DecorationKey; the
AssemblyReference / ClassReference assembly anchors that
the module scans and the architecture tests pin to;
the two data-source attributes (UseDataSourceAttribute,
UseDatabaseAttribute); the settings types this chapter owns,
ApplicationSettings / ModulesSettings /
ModuleSettings / QueryCachePipelineSettings in
Application plus the Infrastructure sections MessageBusSettings,
SmtpSettings, SchedulerSettings and
PushNotificationSettings (the persistence, auth, caching and outbox
sections the same root binds are documented in group 07,
group 08, group 09 and
group 04); the cloud-neutral null-object defaults a vendor adapter
package replaces (NullNativePushSender,
NullPushDeviceRegistrar,
NullFileStorageService) with the vendor-free
NativePushPayloads builder the push adapters share; the two startup
posture checks, StartupConfigurationSummaryService and
CloudAdapterTripwire with its carrier
CloudAdapterTripwireOptions, plus the
ChannelJoinAuthorizerMissingWarningService that
names an open push-channel posture once (the hub tracks each connection's channel memberships and
join budget in a private ConnectionChannels,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:248), the
TransportFailure helper
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Diagnostics/TransportFailure.cs:17) that tells
a transient connect, DNS, dropped-connection or timeout failure from the caller's own cancellation for
every cloud adapter alike (TransportFailure.cs:6-16), and the
RabbitMqConnectionSecurityNoticeService that names a
default-credential or cleartext broker connection; the broker transport boundary
(IBrokerTransport, MessageBusProviders,
BrokerTransportContext,
BrokerTransportPolicies), the transport-neutral broker model it is
written against (BrokerTopology, BrokerSubscription,
BrokerConsumerKind, BrokerNaming,
BrokerHeaders, BrokerWire,
OutgoingBrokerMessage, IncomingBrokerMessage,
IBrokerPublisher, IBrokerReceivePipeline and the
BrokerDisposition family Completed /
Redeliver / DeadLetter), and the two built-in transports
RabbitMqBrokerTransport and
PostgreSqlBrokerTransport with their internals; the cross-replica
locking pair (RedisDistributedLock,
InProcessDistributedLock); the host-scoped job runner
(ScheduledJobRunner) with the
ScheduledJobModelContributor that maps its table, the
ExceptionChain renderer background work records its failures with, and the
PeriodicBackgroundService base (with its private
CycleTurn lock holder) the other fixed-interval sweeps derive from (among them
NotificationCleanupService and the PostgreSQL transport's
PostgreSqlDeadLetterCleanupService); the broker-side
consumer machinery a host composes (IBrokerConsumerBuilder and its
BrokerConsumerBuilder, the
BrokerReceivePipeline behind
IBrokerMessageConsumer, the per-handler
InboxHandlerLoop both broker consumers run their handlers through, and
UpcastingIntegrationEventConsumer<TEvent> with its
UpcastDispatch cache) with the boot-time
EventUpcasterStartupValidator; the scoped
TenantContext and the ambient-context carriers that let a hop off the request
call stack act as the identity that queued the work (AmbientOrigin with its
published OriginSnapshot and RestoreHandle,
ScopedUserOverride,
ImpersonatingCurrentUserService,
ConsumerOriginRestore); the internal-command queue a host composes for
deferred work (IInternalCommand,
IInternalCommandScheduler,
IInternalCommandAdministration with its
InternalCommandDeadLetter projection, the
IInternalCommandDeadLetterHandler<in TCommand>
callback with its InternalCommandDeadLetterNotice, the
InternalCommandNameAttribute that keeps a rename from orphaning
rows and the InternalCommandExecution marker (with its
Scope handle) that tells a handler it is running on the durable path, plus the
ready-made commands the framework ships on it,
IDeleteBlobInternalCommand handled by
DeleteBlobInternalCommandHandlerBase<TCommand>,
and DeleteUserPushInstallationsInternalCommand
handled by
DeleteUserPushInstallationsInternalCommandHandler);
the two resolvers that answer a composition question a plain settings property answered badly,
ApplicationNamespace and
SmtpTransportSecurity; and the shared Users
use-case bases that two apps compose into their own Identity modules. The detailed per-type sections
follow; this overview shows how the pieces fit together at runtime.
[Rubric §7, Microservices Readiness] (assesses whether modules can be enabled, disabled, and
deployed independently with minimal coupling) is the lens this whole chapter is built around: the
module system is the boundary that lets MMCA.ADC run as either a single monolith host or four
separate service processes from the same module code, configuration-switched. [Rubric §12, Performance & Scalability] and [Rubric §3, Clean Architecture] also run throughout: composition is
where the inward-pointing dependency rule gets physically realized (Infrastructure references
Application references Domain references Shared), and where cross-cutting concerns are registered once
for every module rather than per-feature. The ADRs that explain why this shape exists are
ADR-059 (the module
contract itself), ADR-008
(service-extraction topology), ADR-006
(database-per-service) and ADR-014
(the decorator pipeline whose ordering rule this chapter enforces).
The module contract and the boundary it creates
A module is the unit of cohesion above a feature slice: Conference, Engagement, Identity,
Notification. Each one implements IModule
(MMCA.Common/Source/Core/MMCA.Common.Application/Modules/IModule.cs:7): a display Name
(IModule.cs:12), an optional Dependencies list of other module names (IModule.cs:17), a
RequiresDependencies flag (IModule.cs:23), and one Register(services, configuration, applicationSettings) method (IModule.cs:28) that wires all of that module's services. Three of
those five members are default-implemented on the interface (Dependencies => [] at IModule.cs:17,
RequiresDependencies => false at IModule.cs:23, and an empty-bodied RegisterDisabledStubs at
IModule.cs:34), so a leaf module is just Name plus Register. ADC's modules are deliberately
thin: ConferenceModule
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/ConferenceModule.cs:13) is about twenty
lines, just Name plus a Register that forwards to a parameterless AddConferenceModule() extension
method (ConferenceModule.cs:19-20). It does not override RegisterDisabledStubs, and no ADC module
does today: the hook stays on the contract, and the loader still calls it for every disabled module
(MMCA.Common/Source/Core/MMCA.Common.Application/Modules/ModuleLoader.cs:119), so a module whose
cross-module contract another enabled module consumes in-process can register a null-object there.
The crux of the extraction boundary is that one module assembly boots in two topologies. When
Conference runs in its own service, that host names only the Conference module's assembly, so
Engagement does not run there, yet Conference's GetSessionBookmarkCountsHandler still needs
Engagement's IBookmarkCountService. The host's pipeline therefore registers a typed gRPC client
pointed at the real Engagement process with a Replace registration; since nothing else in that host
registers the contract, the call simply adds the scoped gRPC adapter
(MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:323-327, :361). Application code
never learns which path it got; the transport choice lives entirely at the composition edge
(ADR-008). [Rubric §2, Design Patterns] applies here: this is a clean strategy / null-object pairing (real service, disabled
stub, remote client) rather than scattered if (moduleEnabled) checks.
Discovery and Kahn-ordered registration
ModuleLoader
(MMCA.Common/Source/Core/MMCA.Common.Application/Modules/ModuleLoader.cs:16) is the engine. Its one
DiscoverAndRegister overload (ModuleLoader.cs:57-62) takes the assemblies to scan as a required
parameter: there is no AppDomain-scan convenience, and the parameter doc says why, because an
AppDomain scan only sees assemblies already loaded, so a module assembly that is referenced but not
yet touched by any code path would be silently absent from discovery (ModuleLoader.cs:46-51). The
scan guards each GetTypes() call so one bad reference never aborts the whole pass: a
ReflectionTypeLoadException keeps every type that did load, so one unloadable type does not make the
assembly's modules vanish, and any other failure drops just that assembly; both shapes log at Error,
because a module that silently fails to register is an outage that looks like a configuration choice
(ModuleLoader.cs:64-92). It then instantiates every concrete
IModule via Activator.CreateInstance (ModuleLoader.cs:94-97) and every concrete
IModuleSeeder into a case-insensitive dictionary keyed by ModuleName
(ModuleLoader.cs:99-104).
Ordering is Kahn's topological sort (ModuleLoader.cs:249-299) over the modules' declared
Dependencies. Kahn's algorithm is BFS over a dependency graph: compute each module's in-degree
(count of unprocessed dependencies, ModuleLoader.cs:254), build the reverse adjacency list of
dependents (ModuleLoader.cs:257-270), seed a queue with the zero-in-degree modules
(ModuleLoader.cs:273-274), and as each is emitted decrement its dependents' in-degrees, enqueuing
any that reach zero (ModuleLoader.cs:283-287). A dependency name that was never discovered is
skipped rather than treated as an edge (ModuleLoader.cs:264-265); validation catches it later. If
fewer modules come out than went in, the remainder form a cycle and the loader throws with the
offending names (ModuleLoader.cs:291-296). The payoff is an ordering where a module's DI
registrations always exist before any dependent registers, which matters because the CQRS decorator
pipeline (below) can only wrap handlers that are already in the container.
For each sorted module the loader checks ModulesSettings.IsModuleEnabled
(ModuleLoader.cs:116). A disabled module gets RegisterDisabledStubs called
(ModuleLoader.cs:119) and is listed in
DisabledModuleNames (ModuleLoader.cs:120); an enabled one runs ValidateModuleDependencies then
RegisterEnabledModule (ModuleLoader.cs:124-125) and contributes its seeder if one was found
(ModuleLoader.cs:127-130). The loader adds no configuration source of its own: module.Register(...)
receives the host's configuration builder unchanged (ModuleLoader.cs:40-43, ModuleLoader.cs:220), so
a module reads the host's configuration. Dependency validation
(ModuleLoader.cs:176-209) is microservice-aware: a dependency that is disabled in-process but listed
in that consumer's ModuleSettings RemoteDependencies is treated as satisfied
remotely, and only a RequiresDependencies = true module with a genuinely unsatisfied dependency
throws, with an error message that spells out the three ways to fix it (ModuleLoader.cs:190-198).
Every step emits a [LoggerMessage]-generated structured log (ModuleLoader.cs:301-323), so the
startup log tells you exactly which modules loaded, in what order, and how long each took
(ModuleLoader.cs:219-222).
The loader offers no post-build gate for remote dependencies: a remote-declared dependency is trusted
from configuration and logged (ModuleLoader.cs:205-208), and wiring the cross-process replacement
(for example a typed gRPC client) after DiscoverAndRegister returns is the host's job
(ModuleLoader.cs:178-181). [Rubric §13, Observability & Operability] is the category at play in
the log messages above.
The loader is not called from inside AddApplication(), and a host no longer constructs it by
hand either. AddModuleHost in the API layer
(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostExtensions.cs:51) binds and
validates ApplicationSettings and ModulesSettings
(ModuleHostExtensions.cs:61-73), constructs the ModuleLoader with the host's
bootstrap logger, registers it as a singleton (ModuleHostExtensions.cs:75-79), and hands back a
ModuleHostContext whose RegisterModules
method is the discovery step
(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostContext.cs:69-100). Discovery
deliberately does not run inside AddModuleHost: it has to land inside the application pipeline
described next, and its position relative to a host's other steps is a per-host decision
(ModuleHostContext.cs:12-19). After discovery the loader also drives startup data through
SeedAllAsync (ModuleLoader.cs:233-239), which invokes each collected
IModuleSeeder.SeedAsync in registration order.
IModuleSeeder
(MMCA.Common/Source/Core/MMCA.Common.Application/Modules/IModuleSeeder.cs:8) is a two-member
interface, ModuleName (IModuleSeeder.cs:13, matched case-insensitively against an
IModule Name) and SeedAsync(serviceProvider, cancellationToken)
(IModuleSeeder.cs:18), deliberately separate from IModule so seeding runs after the whole
container is built and a real IServiceProvider exists.
The two composition roots, and the pipeline that seals them
Service registration itself lives in two static DependencyInjection classes,
each using a C# extension(IServiceCollection services) block (see
primer §4 for the extension(T) syntax, and
ADR-106 for why
the public DI surface is written that way). The Application root
(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:31) exposes AddApplication()
(DependencyInjection.cs:39), which registers the core singletons
(IDomainEventDispatcher at :41,
IEventUpcasterRegistry at :47,
INavigationMetadataProvider at
:49, IEntityQueryPipeline at :50)
and pulls in the framework's own FluentValidation validators by assembly
(DependencyInjection.cs:70). Each of those four singletons is registered with TryAddSingleton, so
a host that registered its own first keeps it. The upcaster registry is registered unconditionally on purpose: with no upcasters it
is an empty registry whose operations are the identity, so both delivery paths can depend on it
without a null check (DependencyInjection.cs:43-47,
ADR-090), and individual
upcasters accumulate through AddEventUpcaster<TSource, TTarget, TUpcaster>()
(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Extensibility.cs:81).
The Application root also owns ScanModuleApplicationServices<TAssemblyMarker>()
(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:29-31) and its
Assembly-typed overload (DependencyInjection.ModuleScanning.cs:47),
the convention scan every module's AddXModule call makes. It runs on the framework's own scanner, not
a third-party container extension: each step is one AddAssignableTypes call
(MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:59) naming a target
type, a lifetime and a ScanRegistration mode
(ServiceCollectionDecoration.cs:8). Domain-event and integration-event handlers register as
singletons under their interfaces (DependencyInjection.ModuleScanning.cs:53-56); DTO mappers, the
opt-in
IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>
projectors, request mappers and both update-applier shapes register scoped in SelfWithInterfaces
mode, so the class and every interface it implements resolve the same instance within the scope
(DependencyInjection.ModuleScanning.cs:58-76, ServiceCollectionDecoration.cs:13-17); command and
query handlers register scoped under their interfaces (DependencyInjection.ModuleScanning.cs:78-80);
validators come from the module assembly (DependencyInjection.ModuleScanning.cs:82), and finally a
reflection pass TryAdds a CommandRequestValidator<,> for every command implementing
ICommandWithRequest<T> (DependencyInjection.ModuleScanning.cs:84-100) so an explicit validator
still wins. A scan takes every public, non-abstract, non-compiler-generated class assignable to the
target (an open generic target matches any closed implementation on the class or its base types) and
appends, never de-duplicates (ServiceCollectionDecoration.cs:41-44, :251-279).
The order of these calls is a hard contract in exactly one respect, and it is the reason
AddApplicationDecorators() (MMCA.Common.Application/DependencyInjection.cs:145) must come last.
Decoration goes through the same internal helper,
ServiceCollectionDecoration
(MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:47), one source file
linked into each framework project that scans or decorates (ServiceCollectionDecoration.cs:20-24).
Its TryDecorateWith (:115) wraps existing registrations only: for each matching non-keyed
descriptor it moves the original to a keyed copy under a fresh private
DecorationKey (same lifetime, so the container still owns creation and disposal)
and replaces the descriptor in place with a factory that activates the decorator over that copy
(ServiceCollectionDecoration.cs:179-208, :227-241). The position is unchanged, so
last-registration-wins and IEnumerable<T> order survive, and decorating again wraps the previous
decorator, so the one applied last is outermost (ServiceCollectionDecoration.cs:27-31).
DecorationKey compares by reference, not by value, which is what lets stacked decorators each reach
exactly the registration they wrapped (ServiceCollectionDecoration.cs:298-308). An open generic
service type decorates every closed registration of it, closing the decorator over that
registration's type arguments, while an open generic registration cannot be wrapped at all and is
left for VerifyDecoratorPipeline to report (ServiceCollectionDecoration.cs:34-39, :210-225); the
strict DecorateWith<TService, TDecorator> variant throws when nothing is registered yet (:166-177).
So every module's concrete handlers must already be in the container or there is nothing to wrap, and
a handler registered afterwards runs completely unwrapped with nothing failing at startup to say so
(DependencyInjection.cs:266-269). Rather than leaving that as a comment, the framework enforces it.
AddApplicationDecorators() finishes by calling SealPipeline, which TryAdds a singleton instance
of the private marker DecoratorPipelineSeal
(DependencyInjection.cs:191, :368, :411-412), and every registration entry point that
contributes handlers (ScanModuleApplicationServices, AddEntityCrud, AddEntityUpdateVerb,
AddEntityUpdate, AddQueryCaching, AddApplicationDecorators and AddMmcaApplicationPipeline
themselves) opens with ThrowIfPipelineSealed, which scans the collection for that marker and throws
a message naming the offending call (DependencyInjection.cs:414-423). The whole sequence is available as one call,
AddMmcaApplicationPipeline(configure) (DependencyInjection.cs:284-293): it runs AddApplication(),
invokes the callback with a MmcaApplicationPipelineBuilder
(MMCA.Common/Source/Core/MMCA.Common.Application/MmcaApplicationPipelineBuilder.cs:12) whose
ScanModule<TAssemblyMarker> (:27), ScanModules(params Assembly[]) (:41) and
Register(Action<IServiceCollection>) (:62) steps are where module discovery, gRPC clients and
broker messaging go, and then closes with AddApplicationDecorators(). The builder's constructor is
internal precisely so it cannot be created outside that call, because outside it nothing keeps the
decorators last (MmcaApplicationPipelineBuilder.cs:9-14). A third guard, VerifyDecoratorPipeline()
(DependencyInjection.cs:321), is never called automatically: it is the hook an architecture fitness
test calls after replaying a host's own registration sequence. It throws when the pipeline was never
sealed (DependencyInjection.cs:323-328), then takes the effective (last non-keyed) descriptor per
ICommandHandler<,> / IQueryHandler<,> service type and reports every one that has no
implementation factory, which after decoration is proof that nothing wrapped it
(DependencyInjection.cs:330-359).
MMCA.Store/Tests/Architecture/MMCA.Store.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:68 and
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/ApplicationPipelineCompositionTests.cs:160 are
its callers today.
AddApplicationDecorators also encodes the execution order. Each pipeline is written as a list
outermost first (MMCA.Common.Application/DependencyInjection.cs:168-189) and DecorateInExecutionOrder
applies it innermost first, because the decoration applied last is the outermost at runtime
(DependencyInjection.cs:398-409), so the command pipeline ends up
ViewAs -> FeatureGate -> Authorization -> Logging -> Caching -> Validating -> Timeout -> Transactional -> handler
and the query pipeline FeatureGate -> Authorization -> Logging -> Caching -> Validating -> Timeout -> handler (ADR-014); the
command-only ViewAs layer refuses every command from a read-only view-as caller (ADR-137,
DependencyInjection.cs:170). The Caching pair is in neither list unless the host opted in:
AddQueryCaching() (DependencyInjection.cs:223) TryAdds a singleton of the private
QueryCachingOptIn marker (:227, :374), and AddApplicationDecorators()
scans for it (:165, :376-385) and splices the caching decorators in at their ADR-014 position
(:174, :186), leaving every other position unchanged. Because it is a flag read at decoration
time, AddQueryCaching() itself refuses to run once the pipeline is sealed (:225), so it belongs
before AddMmcaApplicationPipeline(...) or inside its callback (:216-218). The
rationale for each position is written out in the method's own doc comment
(MMCA.Common.Application/DependencyInjection.cs:115-143): authorization sits outside caching so a
denied request neither reads nor populates the cache, validation sits outside the transaction so an
invalid command never opens one, and the timeout budget sits inside validation and outside the
transaction so it covers the database work and cancels it rather than leaving it open. The decorator
types themselves (for example
FeatureGateCommandDecorator<TCommand, TResult>,
AuthorizationCommandDecorator<TCommand, TResult>
and TimeoutCommandDecorator<TCommand, TResult>)
are documented in the CQRS-pipeline chapter; this chapter owns only the wiring of them. An optional
MiniProfiler pair is registered separately by an opt-in AddApplicationProfiling()
(MMCA.Common.Application/DependencyInjection.cs:237, wrapping through TryDecorateWith at :239-240),
never by AddApplicationDecorators(); the composed
service host makes that call after the sealed pipeline when ApplicationSettings:UseMiniProfiler is true
(MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:162-165).
[Rubric §6, CQRS & Event-Driven] and [Rubric §1, SOLID] (open/closed) live here: cross-cutting
behavior is added by wrapping, not by editing handlers.
The Infrastructure root
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:49) exposes
AddInfrastructure(configuration) (DependencyInjection.cs:59), which binds most of the settings
types in this chapter, registers the three save interceptors as singletons
(DependencyInjection.cs:66-72), the persistence stack (data-source service and resolver, entity
registry, the scoped and singleton context factories, repositories, unit of work,
DependencyInjection.cs:61-132), scans the framework's own EF entity configurations through the same
AddAssignableTypes helper (DependencyInjection.cs:141-145), adds caching
(DependencyInjection.cs:147), registers the refresh
session store and its retention sweep behind the same flag that maps the table
(DependencyInjection.cs:185-191, :225-233), and enrolls four startup checks through TryAddEnumerable, so a
host whose modules each call AddInfrastructure still runs each once: a validator that fails the host
on a bad upcaster graph (DependencyInjection.cs:262-263), a validator that fails it on a navigation
its data source cannot include and no populator loads (:257-258), the one-line
StartupConfigurationSummaryService (:263-264), and the
CloudAdapterTripwire carried through ValidateOnStart by
CloudAdapterTripwireOptions (:270-272), both described in the
settings section below. The outbox hosted services are conditional: the
method reads MessageBusSettings, calls EnsureOutboxAvailableForProvider, and
adds OutboxProcessor plus OutboxCleanupService only
when IsOutboxEnabled, otherwise registering
OutboxDisabledNoticeService so the choice is
visible in the log (DependencyInjection.cs:294-306,
ADR-100).
The OutboxMessages table stays mapped either way, so flipping the flag is never a migration
(DependencyInjection.cs:288-293). It closes by composing the internal-command queue
(AddInternalCommands, DependencyInjection.cs:313), running AddServices() (:303) and then
layering the impersonation decorator over whatever ICurrentUserService that left registered, through
TryDecorateWith (:305-312), both described two sections below. Optional add-ons sit alongside the root:
the class is partial, split by concern across sibling files, so
AddCommonHybridCache (DependencyInjection.Caching.cs:158), AddScheduledJobs
(DependencyInjection.Jobs.cs:37), AddTwoFactorAuthentication (DependencyInjection.Auth.cs:40),
AddEmailConfirmation (:68), AddLegalAcceptance (:104), AddStoredPermissionGrants (:139),
AddAuditTrail (DependencyInjection.Jobs.cs:108), AddMultiTenancy (DependencyInjection.cs:359),
AddServices (:373), AddEntityConfigurationAssembly (:432), AddStronglyTypedIds (:460),
AddNpgsqlDataSourceConfigurator (DependencyInjection.Persistence.cs:24),
AddNotificationInfrastructure (DependencyInjection.Notifications.cs:23), AddPushNotifications
(:38), and the broker pair AddBrokerMessaging (DependencyInjection.Messaging.cs:48) and
AddBrokerTransport (:159), the registration call an adapter package's transport goes through.
Native push, file storage and a non-built-in broker are not registered by any method of this class:
each arrives from a vendor adapter package that replaces a core default (see
group 28).
AddCaching (MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:29) also registers this chapter's
one cross-replica primitive: an IDistributedLock that
resolves to RedisDistributedLock when the host has an
IConnectionMultiplexer registered, and to the warn-once
InProcessDistributedLock otherwise
(MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:115-129). The Redis implementation is the
standard SET key token NX PX ttl acquire
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/RedisDistributedLock.cs:67) with a
compare-and-delete release script (RedisDistributedLock.cs:36-37, evaluated at :114), handing back
a RedisLockHandle that releases exactly its own acquisition, once
(RedisDistributedLock.cs:91, :101). That release runs after the guarded work has already
committed, so a Redis fault there is logged rather than thrown and the key falls back to expiring on
its TTL, and a release that finds the key already gone logs that the section was not exclusive
(RedisDistributedLock.cs:106-129); the fallback is exclusive only inside one process, which is exactly
what its warning says out loud
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/InProcessDistributedLock.cs:74-75),
and its InProcessLockHandle simply removes the key from a
ConcurrentDictionary (InProcessDistributedLock.cs:79-91). A multi-replica host that registers no
Redis client therefore gets one execution of the guarded section per replica. [Rubric §29, Resilience] and [Rubric §12, Performance & Scalability] both touch this pair: the degradation is
deliberate, announced, and never silent.
Opt-in platform features are composed the same way
Four capabilities are registered beside the roots rather than inside them, and they share one
discipline: registering a feature is not the same as turning it on. AddScheduledJobs(configuration)
(MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:37) binds
SchedulerSettings and enrolls ScheduledJobRunner
through TryAddEnumerable rather than AddHostedService, precisely so two modules calling it cannot
start two runners racing for the same rows (DependencyInjection.Jobs.cs:44-48); individual
IScheduledJob implementations arrive through
AddScheduledJob<TJob>() (DependencyInjection.Jobs.cs:72), each registered scoped so the runner can
resolve it in a fresh scope per execution. AddAuditTrail(configuration)
(DependencyInjection.Jobs.cs:108) binds AuditTrailSettings, adds the
AuditTrailSaveChangesInterceptor
and the AuditTrailReader that projects
the trail's rows, and contributes its own retention job
(DependencyInjection.Jobs.cs:110-124), which only actually runs when the host also enabled the scheduler.
AddMultiTenancy(configuration) (DependencyInjection.cs:359) binds
TenancySettings and registers
TenancySettingsValidator as an IValidateOptions<TenancySettings>
through TryAddEnumerable (DependencyInjection.cs:361-376); note what it does not do, because
that is the design:
TenantSaveChangesInterceptor and
ITenantContext, whose scoped implementation
TenantContext reports IsResolved = false until a request calls SetTenant
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/TenantContext.cs:26, :28, registered
at DependencyInjection.cs:396) unless it was constructed inside a background hop, in which case it
starts with the tenant that hop restored (TenantContext.cs:20, see the deferred-work section below),
are registered unconditionally by
AddInfrastructure and AddServices and stay inert until a tenant is resolved, so the framework can
never sit in the half-wired state where entities carry
ITenantEntity but the write-side guard is off
(DependencyInjection.cs:69-72, :379-383,
ADR-073). Finally
AddUserDataExportSection<TSection>() (MMCA.Common.Application/DependencyInjection.Extensibility.cs:38)
accumulates IUserDataExportSection contributors into the one
IEnumerable the export handler fans out over. The governing ADRs are
ADR-074,
ADR-075, ADR-073 and
ADR-076; [Rubric §30, Compliance & Data Governance] is the category the trail and the export both serve.
ScheduledJobRunner
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobRunner.cs:40) is the one
of these with real runtime machinery, and it reuses the outbox's idioms wholesale. It is a
BackgroundService that returns immediately (after one log line) when Scheduler:Enabled is false
(ScheduledJobRunner.cs:92-97), waits out a 15-second startup delay so migrations finish first
(ScheduledJobRunner.cs:70, :95), then loops: run one cycle that reconciles the ScheduledJobs rows
against the registered jobs, claims due rows with a lease, executes and stamps the outcome
(ScheduledJobRunner.cs:109-114, :213), and smart-waits until the earliest upcoming occurrence capped
at Scheduler:PollingIntervalSeconds (ScheduledJobRunner.cs:129-137). A claim attempt is a single
filtered ExecuteUpdateAsync against the still-unleased predicate, so two racing replicas both issue
it and exactly one matches (ScheduledJobRunner.cs:471-481); it returns a JobClaim
carrying either this replica's lock token or null when another replica won the row
(ScheduledJobRunner.cs:483), which is what makes an occurrence run exactly once across a scaled host.
The persisted row is ScheduledJobEntry
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobEntry.cs:20), deliberately
not an auditable entity: it is framework bookkeeping with an explicit claim lease instead of a
concurrency token, and it is host-scoped, living in the Default data source only
(ScheduledJobEntry.cs:8-19), on whichever relational engine Scheduler:DataSource names (SQL Server
unless set, and never Cosmos because the table is relational, SchedulerSettings.cs:48-55), which
each cycle resolves before touching the table (ScheduledJobRunner.cs:232-233). SchedulerMetrics
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/SchedulerMetrics.cs:16) publishes the
MMCA.Common.Scheduler meter with a run counter tagged by job and outcome
(SchedulerMetrics.cs:28-31), a duration histogram (SchedulerMetrics.cs:39-42) and a schedule-lag
histogram (SchedulerMetrics.cs:50), the same shape BrokerMetrics
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMetrics.cs:18) uses for the
MMCA.Common.Broker meter's fault and circuit-open counters (BrokerMetrics.cs:30, :43). So
[Rubric §13, Observability & Operability] is covered by instruments rather than by log scraping.
Two more composition-time shapes sit beside those registrations. The first is the base class the
other periodic sweeps derive from: PeriodicBackgroundService
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Hosting/Background/PeriodicBackgroundService.cs:31)
factors the fixed-interval pattern into one place, an IsEnabled gate evaluated once at startup
(PeriodicBackgroundService.cs:49), a StartupDelay defaulting to 15 seconds (:31), then
ExecuteCycleAsync on an Interval loop (:25, :50) whose failing cycle is logged and never kills
the loop (through an overridable LogCycleFailure, :45-46, so a derived sweep can keep its own
message and the event id its dashboards and tests key on, :40-43), with every wait going through an injected TimeProvider so a test can drive it on a fake clock
(PeriodicBackgroundService.cs:9-13); its own doc comment records that the outbox processor
deliberately does not use it, because a signal-driven smart wait is not a fixed interval (:13-15).
A derived sweep that must run on one replica only overrides CycleLock (PeriodicBackgroundService.cs:55,
keyed by CycleLockKey at :62), and the private CycleTurn (:149) is that
replica's hold on it: released and re-taken at the start of each cycle, so the holder keeps the turn
while it lives and the lock's time to live hands the turn over when it does not (:145-148).
The second is the broker side of AddBrokerMessaging. There is no per-consumer fault consumer: a
message whose handlers exhaust every retry and redelivery is dead-lettered by the framework's receive
pipeline, which logs it and counts broker.fault.count at that point
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerConsumerBuilder.cs:11-13;
the pipeline is described in the broker section below). A retired contract is bound instead to
UpcastingIntegrationEventConsumer<TEvent>
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastingIntegrationEventConsumer.cs:30)
through RegisterUpcastedIntegrationEventConsumer<TEvent>, which upcasts each message to its terminal
contract through
IEventUpcasterRegistry and dispatches the
handlers registered for that contract, so handlers are written once against the newest event type
while producers still publishing the old one keep being delivered, with deduplication still keyed on
the original message id (UpcastingIntegrationEventConsumer.cs:10-26,
ADR-090). Registering both
kinds for one type is refused at registration rather than left to run the handlers twice
(UpcastingIntegrationEventConsumer.cs:18-19, enforced at
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:51-58).
Because the terminal type is known only at runtime, handler resolution goes through
UpcastDispatch
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastDispatch.cs:15), which
caches the closed handler interface and a compiled invoker per terminal type so reflection stays off
the per-message path (UpcastDispatch.cs:7-14, used at UpcastingIntegrationEventConsumer.cs:90).
The upcaster graph those hops depend on
is checked at boot by EventUpcasterStartupValidator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/EventUpcasterStartupValidator.cs:20),
an IHostedService that AddInfrastructure enrolls through TryAddEnumerable
(MMCA.Common.Infrastructure/DependencyInjection.cs:262-263): resolving the registry is the check,
because its constructor rejects a duplicate source, a self-mapping and a cycle, so a misconfigured
host fails to start instead of dead-lettering events hours later
(EventUpcasterStartupValidator.cs:7-17, :23-29).
Deferred work, and the context that travels with it
The last two things AddInfrastructure composes are a queue for work a request wants done later, and
the machinery that lets whatever drains a queue act as the identity that filled it.
AddInternalCommands (MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:150, called at
DependencyInjection.cs:313) binds InternalCommandsSettings, registers the origin capture, the
scheduler and the operator surface scoped (DependencyInjection.Jobs.cs:160-161, :166), and then
takes the outbox's posture deliberately: the table is mapped either way, and InternalCommands:Enabled
decides only whether the processor and its retention sweep run (DependencyInjection.Jobs.cs:174-177)
or a disabled-notice hosted service says so once in the log (:179, rationale at :130-139).
IInternalCommand
(MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IInternalCommand.cs:38) is the
whole application-side contract, a marker over ICommand<Result> with no second handler
interface: a deferred command is executed by the same ICommandHandler<TCommand, TResult> a
synchronous one is, so every decorator (feature gate, authorization, logging, validation, timeout,
transaction) applies to the deferred execution exactly as it does inline (IInternalCommand.cs:11-16).
The two rules that follow from a row in a table are stated on the interface itself: the payload must
round-trip through System.Text.Json, and execution is at-least-once because a host that dies between
the handler's commit and the row's stamp re-runs the row once the lease expires, so handlers must be
idempotent (IInternalCommand.cs:19-29). IInternalCommandScheduler
(IInternalCommandScheduler.cs:16) writes the row on the caller's own unit of work: scheduling
from inside an ITransactional command commits with the aggregate change or rolls back with it
(IInternalCommandScheduler.cs:9-14), which is the outbox's atomicity guarantee applied to
work the host wants to do rather than to a message it wants to publish. With a transaction active the
row is only enrolled, and when no later save follows the transactional pipeline saves it just before
the commit; with none active the row is saved at once, flushing whatever else is pending on that
context (IInternalCommandScheduler.cs:38-47). Both overloads return
Result<Guid> (IInternalCommandScheduler.cs:49-52, :59-62), the handle the administration surface
takes. A row stores the command's assembly-qualified CLR name unless
InternalCommandNameAttribute
(InternalCommandNameAttribute.cs:25) declares a stable identity, the internal-command twin of
EventNameAttribute on the outbox side, with the same drain-then-rename caveat because the attribute
changes only what new rows store (InternalCommandNameAttribute.cs:12-17).
IInternalCommandAdministration
(IInternalCommandAdministration.cs:17) is the operator half: count the pending backlog, page the
dead letters as InternalCommandDeadLetter rows
(IInternalCommandAdministration.cs:102) whose command payload is deliberately not projected because
it can carry personal data (:86-89), requeue them (attempts reset, the lease and dead-letter stamp
cleared, LastError kept on purpose, :48-53), and purge completed rows on demand. Every method
returns a Result, because an unknown source name is an expected failure an admin screen renders
rather than an exception. A command that must leave a trace when it is abandoned registers an
IInternalCommandDeadLetterHandler<in TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IInternalCommandDeadLetterHandler.cs:34):
its HandleAsync (:42) runs once after the dead-letter stamp is written, in a fresh scope with the
scheduling user, tenant and correlation id restored but outside the command pipeline, and receives an
InternalCommandDeadLetterNotice
(InternalCommandDeadLetterNotice.cs:14) naming the row, the attempts_exhausted or
handler_missing reason, the recorded error and the attempt count (InternalCommandDeadLetterNotice.cs:5-13).
The callback is best-effort (an exception is logged and swallowed, never retried) and a requeue does
not undo what it recorded (IInternalCommandDeadLetterHandler.cs:12-28). [Rubric §13, Observability & Operability] and [Rubric §29, Resilience]
are the categories: without this surface, a command that exhausted its attempts has no way back into
execution except hand-edited production SQL.
The framework ships one ready-made use of the queue, for the case an inline call handles worst:
deleting a blob that a committed change left orphaned.
IDeleteBlobInternalCommand
(MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IDeleteBlobInternalCommand.cs:21)
adds a single BlobName (IDeleteBlobInternalCommand.cs:24) to
IInternalCommand, because a delete run in the post-commit tail is best effort
(a storage outage, a deploy or a crash leaks the blob with nothing left that knows about it) while a
row scheduled on the same unit of work survives all three (IDeleteBlobInternalCommand.cs:9-13). An
implementation is a small record carrying only the name, with an
InternalCommandNameAttribute so a later rename cannot strand rows
in flight (IDeleteBlobInternalCommand.cs:16-18).
DeleteBlobInternalCommandHandlerBase<TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/DeleteBlobInternalCommandHandlerBase.cs:28)
is the idempotent handler the at-least-once rule asks for: a successful delete completes the row, a
NotFound answer is already the state the command asks for and so also returns Result.Success()
instead of retrying forever, and any other failure is returned unchanged so the processor's backoff
retries it (DeleteBlobInternalCommandHandlerBase.cs:45-64, rationale at :13-18). A consumer
derives one sealed subclass per command, so the handler scan registers a closed
ICommandHandler<TCommand, Result> that the decorators wrap, and overrides only BlobKind (default
"Blob", DeleteBlobInternalCommandHandlerBase.cs:38) to label its log lines (:20-23). ADC does
this twice, for avatars
(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteAvatarBlob/DeleteAvatarBlobInternalCommandHandler.cs:20)
and for session assets
(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/DeleteSessionAssetBlob/DeleteSessionAssetBlobInternalCommandHandler.cs:20);
Store has no subclass. The storage side is
ADR-045.
Context propagation is the other half, and it is one helper rather than one per mechanism.
AmbientOrigin
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:21) is the single place
the framework captures and restores the five values a hop off the call stack needs (user id, roles,
permission claims, tenant, correlation id), so a deferred command, an outbox row and a broker message
all carry the same set the same way (AmbientOrigin.cs:10-19). Roles travel as one comma-separated
value bounded by the column width, MaxRolesLength = 512 (AmbientOrigin.cs:40), keeping only the
whole leading roles that fit, because cutting a name mid-word would restore a role nobody holds
(AmbientOrigin.cs:55-60); the flattener is null-tolerant on purpose, because
ICurrentUserService.Roles is a default interface member that hand written test doubles routinely
leave unstubbed and a null there must read as "no roles", never as a capture that throws inside a
save (AmbientOrigin.cs:47-53). Permission claims are the opposite trade: FlattenPermissions
(AmbientOrigin.cs:110) writes them as a JSON array at full fidelity, because a dropped permission
would deny a deferred command the inline request was allowed to run and no delimiter is safe for an
arbitrary permission name (AmbientOrigin.cs:97-107), and ParsePermissions (:135) reads a
malformed value back as no permissions rather than failing the hop (:128-132). The mfa claim is
deliberately not carried: a step-up proves a live interaction, so an IRequiresMfa command cannot run
deferred (AmbientOrigin.cs:163-167). The capture sites are the internal-command
origin capture
(InternalCommandOriginCapture,
.../Persistence/InternalCommands/InternalCommandOriginCapture.cs:34), the outbox writer
(.../Persistence/DbContexts/Factory/DbContextFactory.cs:158) and the broker publisher
(.../Messaging/BrokerMessageBus.cs:105); the restore sites are the internal-command processor
(.../Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:483), the
OutboxProcessor
(.../Persistence/Outbox/Processing/OutboxProcessor.cs:508) and the consumers.
Restore (AmbientOrigin.cs:255) does two things. It writes the captured values onto the scope it was
given, tenant first because the tenant routes the scoped context factory, then the principal, then the
correlation id (AmbientOrigin.cs:269-289); the principal is always overwritten or cleared so a reused
scope cannot let one message's user answer for the next, while the tenant is set only when the scope has
not already resolved a different one, because a tenant cannot change within a scope
(AmbientOrigin.cs:214-225, :294-303). And it publishes what the scope ended up with as an
OriginSnapshot
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:377) on an AsyncLocal
(AmbientOrigin.cs:26, read through Current at :34, published at :279-285), returning a
RestoreHandle (AmbientOrigin.cs:364) whose Dispose puts back whatever origin
was published before (AmbientOrigin.cs:266-267, :287, :342). The publication exists because integration
event handlers are singletons that open their own scope from the root factory, a scope the direct
restore never reaches; so TenantContext, ScopedUserOverride
and CorrelationContext seed themselves from
Current once, when constructed (AmbientOrigin.cs:231-242, TenantContext.cs:20,
ScopedUserOverride.cs:30, CorrelationContext.cs:13), and a handler's own scope still runs as the
original interaction. The snapshot is a six-value record (user id, roles, permission claims, tenant,
correlation id, authentication type, AmbientOrigin.cs:377-383) whose BuildPrincipal (:363)
rebuilds the claims principal through the same AmbientOrigin.BuildPrincipal the direct restore uses
(AmbientOrigin.cs:179-206, :271): the user id as sub, each role as a role claim and each
permission as a permission claim, so deferred work is granted exactly as the inline request was
(AmbientOrigin.cs:154-160). Suppress (AmbientOrigin.cs:355) withdraws the published
origin behind the same handle type for the one place an explicit choice must win over an enclosing hop,
TenantDataSourceTargets
CreateTenantScope (.../Persistence/DataSources/TenantDataSourceTargets.cs:105). Every restore site
holds the handle for the whole row or message (using var origin, for example
UpcastingIntegrationEventConsumer.cs:69), so the next one cannot inherit it.
A restore lands in ScopedUserOverride
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ScopedUserOverride.cs:27), a per-scope
carrier holding the principal that did not arrive over HTTP (ScopedUserOverride.cs:30, set at :36).
The principal itself is never a live ambient value: a scope created during a hop copies the published
origin once, at construction, and owns that copy from then on, so nothing is shared or mutated across
scopes, and an HTTP request (which never publishes an origin) resolves an empty carrier and reads
straight through to the HTTP principal (ScopedUserOverride.cs:17-26). It exposes Clear() (:50)
because the outbox processor keeps one scope for a whole batch and without an explicit clear a row
raised by a user would answer for every later row raised by the system
(ScopedUserOverride.cs:42-50). The carrier is read by
ImpersonatingCurrentUserService
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ImpersonatingCurrentUserService.cs:20),
which decorates rather than replaces whatever
ICurrentUserService the host registered: with no override
every member reads straight through to the inner service, so an HTTP request behaves exactly as it did
before the decorator existed (ImpersonatingCurrentUserService.cs:25-35), and claim values are parsed
in the invariant culture exactly as CurrentUserService writes them (:46-50). AddInfrastructure
applies it with the framework's own TryDecorateWith after AddServices() has run its own
TryAddScoped, guarded on the presence of the ScopedUserOverride registration so a host whose
modules each call AddInfrastructure does not stack one wrapper per call
(DependencyInjection.cs:317-324). The broker side of the same restore is
ConsumerOriginRestore
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/ConsumerOriginRestore.cs:20),
the one step of the restore that knows about a transport (ConsumerOriginRestore.cs:13-19): its
Apply (ConsumerOriginRestore.cs:31) reads the headers BrokerMessageBus stamped (user id, roles,
permissions, tenant, correlation id) from the delivered message's string dictionary, hands them to
AmbientOrigin.Restore, and returns the restore handle the consumer holds for the whole consume
(ConsumerOriginRestore.cs:45-52, the permissions header at :49). It is shared by every consumer
the receive pipeline dispatches to, both
IntegrationEventConsumer<TEvent>
(.../Messaging/Consumers/IntegrationEventConsumer.cs:76) and
UpcastingIntegrationEventConsumer<TEvent>
(UpcastingIntegrationEventConsumer.cs:65), each calling it before the inbox is touched because under
database-per-tenant the restored tenant routes the inbox store (UpcastingIntegrationEventConsumer.cs:60-64),
so a message reaching a retired contract is restored exactly as one reaching the current contract. The
user id is transported as text and parsed back, and a malformed value is treated as a publisher bug
that yields no identity rather than a reason to fail the consume (ConsumerOriginRestore.cs:35-43);
every broker header is a string in the first place, so a broker that widens or retypes application
properties cannot change what the receiver reads
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerHeaders.cs:3-7).
[Rubric §11, Security] is the lens: the identity a background
execution acts as is captured from the request that queued it, never assumed or elevated.
The broker transport boundary
AddBrokerMessaging
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:63) owns
everything that is the same on every broker and hands only the byte-moving part to one
IBrokerTransport
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/IBrokerTransport.cs:22).
The transports are framework code with no third-party messaging library underneath
(ADR-118), and the
contract states the division itself: the framework owns the topology, the wire format, the receive
pipeline (origin restore, inbox, retry, redelivery and dead-letter decisions), the outbox-only publish
path and the tracing, while a transport publishes an outgoing message to a topic, delivers each message
on the host's queue to the receive pipeline, and carries out the disposition the pipeline returns
(IBrokerTransport.cs:7-15). RabbitMQ and PostgreSQL are built in and every other transport ships in
an adapter package, so the core packages never reference a vendor SDK (IBrokerTransport.cs:16-20).
The contract is three members: a Name compared case-insensitively against MessageBus:Provider
(IBrokerTransport.cs:28), a MaxRedeliveryDelay that is null when the broker has no delay cap
(:35; Amazon SQS caps a message delay at 15 minutes, :30-34), and Register(services, context)
(:51), which adds a singleton IBrokerPublisher and a hosted receiver for the
host's queue, and which runs while AddBrokerMessaging runs so a missing namespace or connection
string throws at startup rather than at the first publish (IBrokerTransport.cs:37-47).
IBrokerPublisher
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerPublisher.cs:9) is called
only by BrokerMessageBus, which the outbox processor drains through, so a publish the broker did not
accept must throw and surface to the outbox's retry and circuit breaker (IBrokerPublisher.cs:3-8,
PublishAsync at :18).
MessageBusProviders
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/MessageBusProviders.cs:10)
names the three values the core handles itself, InProcess (the default when the setting is absent,
MessageBusProviders.cs:16), RabbitMq (:19) and PostgreSql (:27), and keeps a small map from
the adapter-supplied names (AzureServiceBus, AmazonSqs) to the package and call that provide them,
used only to make the registration error actionable (MessageBusProviders.cs:29-39).
ResolveBrokerTransport constructs a built-in transport directly, otherwise takes the last registered
IBrokerTransport whose name matches, otherwise throws naming the package to reference (or the
AddBrokerTransport call to make) and the available providers
(MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:214-247); an adapter therefore calls
AddBrokerTransport (:174, a TryAddEnumerable singleton that rejects an empty name, :178-183)
before the host calls AddBrokerMessaging.
The registration order inside AddBrokerMessaging is a sequence of startup guards. It returns at once
for InProcess (DependencyInjection.Messaging.cs:72), fails a broker paired with an explicitly
disabled outbox because the outbox is a broker host's only publish path (:80, rationale at
:234-255), resolves the transport (:84), and then requires Application:Namespace (:89,
:257-281): every topic is prefixed with it, so services that fell back to their own application
names would publish and subscribe on different topics and lose every cross-service event with no error
anywhere. Consumers are declared next. The configureConsumers callback receives an
IBrokerConsumerBuilder
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerConsumerBuilder.cs:16)
with two calls, RegisterIntegrationEventConsumer<TEvent> (:26) and, for a retired contract,
RegisterUpcastedIntegrationEventConsumer<TEvent> (:40). There is one queue per host, so two
services consuming the same event never compete for one queue and there is no per-consumer endpoint
configuration to get wrong (IBrokerConsumerBuilder.cs:9-14). The internal
BrokerConsumerBuilder
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:12)
records one BrokerSubscription
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerSubscription.cs:11) per
event, tagged with its BrokerConsumerKind (BrokerConsumerKind.cs:4) and
named through BrokerNaming (BrokerNaming.cs:13), throws on a second registration
of the same event in either kind (BrokerConsumerBuilder.cs:47-58), and maps each subscription to the
closed IntegrationEventConsumer<TEvent> or UpcastingIntegrationEventConsumer<TEvent>
(BrokerConsumerBuilder.cs:36-45), which AddBrokerMessaging registers scoped
(DependencyInjection.Messaging.cs:105). The collected subscriptions become the host's
BrokerTopology
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerTopology.cs:10): the
application namespace, the one queue (MessageBus:QueueName or the application name,
DependencyInjection.Messaging.cs:94-96) and the subscriptions in registration order, with a
constructor that rejects a duplicate event name a second time (BrokerTopology.cs:25-34). A host that
consumes nothing still has a topology: it publishes, and its transport creates no queue
(BrokerTopology.cs:7-8). The method then registers the receive pipeline (:109), Replaces the bus
interfaces (:119, :125) and the inbox store (:132-147), and calls transport.Register last, so
the transport sees every framework registration above it (:150-158).
The transport receives a BrokerTransportContext
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/BrokerTransportContext.cs:11):
the topology, also registered as a singleton so a hosted receiver can take it from DI
(BrokerTransportContext.cs:34-38), the bound MessageBusSettings (:41), the
connection string resolved from MessageBus:ConnectionString, then ConnectionStrings:rabbitmq, then
ConnectionStrings:messaging, or null so the transport keeps its own default host (:43-48), and
the configuration for transport-specific keys (:51).
Every delivered message goes through one IBrokerReceivePipeline
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerReceivePipeline.cs:16),
whose single ProcessAsync takes an IncomingBrokerMessage
(IncomingBrokerMessage.cs:11) and returns a BrokerDisposition
(IBrokerReceivePipeline.cs:22). Its implementation,
BrokerReceivePipeline
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:27),
restores the publisher's trace context as the parent of a Consumer span, resolves the subscription from
the event-name header, deserializes the body, and runs the subscription's consumer (inbox, origin
restore, handlers) through the non-generic IBrokerMessageConsumer
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IBrokerMessageConsumer.cs:12)
with in-process exponential retry, each attempt in a fresh DI scope (BrokerReceivePipeline.cs:12-20).
The disposition is a closed record family (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerDisposition.cs:8):
Completed (:14, shared as Complete at :11), Redeliver carrying a
delay and the next redelivery count (:24), and DeadLetter carrying a reason and a
detail (:33); a transport applies it and decides nothing itself, because retry counts, intervals and
dead-letter policy live once, in the pipeline (BrokerDisposition.cs:3-7). An unknown event name or a
body that does not deserialize is dead-lettered at once as unknown-event or poison
(BrokerReceivePipeline.cs:30, :32, :124-144); a message whose retries all fail is redelivered
while intervals remain (:166) and is dead-lettered as handler-failed after that (:35, :176),
with one Error log and one broker.fault.count increment at that point (:17-19). It never throws for
a handler or payload failure: only the host's own cancellation escapes, and the transport then leaves
the message unacknowledged so the broker delivers it again (BrokerReceivePipeline.cs:21-24). On the
wire, OutgoingBrokerMessage (OutgoingBrokerMessage.cs:13) is what a
publisher sends, BrokerHeaders (BrokerHeaders.cs:8) names the transport-level
headers (event name, the message id the inbox dedupes on, the redelivery count, W3C trace context,
:10-29), and BrokerWire
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerWire.cs:12) holds the two pieces
both hops must agree on: the MMCA.Common.Messaging trace source (BrokerWire.cs:19) and body JSON
options identical to the outbox payload's, so an event that round-trips through the outbox
round-trips through the broker in the same shape (:27-37).
BrokerTransportPolicies
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/BrokerTransportPolicies.cs:18)
holds the receive-side policies as pure functions of MessageBusSettings, so the pipeline and every
transport read one definition (BrokerTransportPolicies.cs:3-10). RetryDelay (:27) doubles
RetryMinIntervalSeconds per retry up to RetryMaxIntervalSeconds, so the defaults wait 1, 2, 4, 8 and
16 seconds (:18-23). BuildRedeliveryIntervals (:52, :65) maps the second-level intervals
(one minute, ten minutes, one hour by default, MessageBusSettings.cs:196), drops non-positive entries
because a zero interval would turn the second level into a hot loop, and clamps each to the
transport's MaxRedeliveryDelay (BrokerTransportPolicies.cs:53-86); the pipeline reads the clamped
set once, at construction (BrokerReceivePipeline.cs:87). In-process retry absorbs a blip measured in
seconds, redelivery an outage measured in minutes or hours, and every in-process retry is exhausted
before a redelivery is asked for (BrokerTransportPolicies.cs:11-17). The backpressure knobs,
ResolvePrefetchCount (:85) and ResolveConcurrentMessageLimit (:98), are range-guarded in code
rather than by [Range], because AddBrokerMessaging binds the section with
Get<MessageBusSettings>(), which never runs DataAnnotations, and a value of zero or less leaves the
transport's own default in place (:77-82).
Two transports are built in, written against the same contract an adapter implements.
RabbitMqBrokerTransport
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqBrokerTransport.cs:25)
runs on RabbitMQ.Client. Its topology, named by RabbitMqNames
(RabbitMqNames.cs:19), is a durable fanout exchange per topic, one durable queue per host bound to
the exchange of every event it consumes, {queue}-error for dead letters, and a
{queue}-delay-{seconds}s queue per redelivery interval whose message time to live returns each
message to the host queue, so delayed redelivery needs no broker plugin; publishes are persistent and
confirmed, and connections recover automatically (RabbitMqBrokerTransport.cs:12-18). Register
(:33-61) adds a RabbitMqPublisher (RabbitMqPublisher.cs:10) over a
RabbitMqChannelOperations (RabbitMqChannelOperations.cs:12) and a
RabbitMqConnectionSource (RabbitMqConnectionSource.cs:11) with a
RabbitMqProvisioner (RabbitMqProvisioner.cs:16), returns early when the
topology has no subscriptions (RabbitMqBrokerTransport.cs:59-62), and otherwise adds a hosted
RabbitMqReceiver (RabbitMqReceiver.cs:22) whose concurrency is
ConcurrentMessageLimit or else the processor count and whose prefetch is PrefetchCount or else
twice the concurrency (RabbitMqBrokerTransport.cs:102-118). The connection string must be an
amqp:// or amqps:// URI or registration throws; with none the client's localhost:5672 default
applies (:19-21, :70-86). Default guest/guest credentials (a missing connection string
included) or a cleartext amqp:// URI outside Development add a hosted
RabbitMqConnectionSecurityNoticeService
(RabbitMqConnectionSecurityNoticeService.cs:16, registered at RabbitMqBrokerTransport.cs:46-52)
that logs one startup Warning and still connects as configured (RabbitMqConnectionSecurityNoticeService.cs:6-11).
RabbitMqDispositionApplier
(RabbitMqDispositionApplier.cs:21), RabbitMqHeaders (RabbitMqHeaders.cs:11)
and IRabbitMqOperations (IRabbitMqOperations.cs:9) complete the internal
set. PostgreSqlBrokerTransport
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:39)
keeps topics, queues and delayed redeliveries in three tables of one PostgreSQL database, defined by
PostgreSqlTransportSql (PostgreSqlTransportSql.cs:24), and is core
rather than an adapter because any PostgreSQL is the broker (PostgreSqlBrokerTransport.cs:11-16). A
publish inserts one row per subscribed queue in one statement and wakes the receivers with
pg_notify; a receiver claims rows with FOR UPDATE SKIP LOCKED under a renewed lease and falls back
to polling; a redelivery pushes the row's visible_after out, so there is no delay cap; and a dead
letter moves the row to {schema}.dead_letters (PostgreSqlBrokerTransport.cs:17-23). Register
(:61-94) adds the PostgreSqlMessageStore (PostgreSqlMessageStore.cs:16)
singleton and the PostgreSqlPublisher (PostgreSqlPublisher.cs:13), then the
PostgreSqlSchemaMigrator (PostgreSqlSchemaMigrator.cs:12) when
MigrateOnStartup is on, ahead of the receiver because hosted services start in registration order
(PostgreSqlBrokerTransport.cs:78-82), and finally the PostgreSqlReceiver
(PostgreSqlReceiver.cs:27) with its PostgreSqlReceiverOptions
(PostgreSqlReceiverOptions.cs:11, PostgreSqlBrokerTransport.cs:89-96);
IPostgreSqlMessageStore (IPostgreSqlMessageStore.cs:10),
PostgreSqlClaimedMessage (PostgreSqlClaimedMessage.cs:14) and
PostgreSqlDispositionApplier (PostgreSqlDispositionApplier.cs:17)
complete the set. Unlike RabbitMQ there is no default host, so a missing connection string fails
registration (PostgreSqlBrokerTransport.cs:125-131). Dead letters do not pile up unbounded: a hosted
PostgreSqlDeadLetterCleanupService
(PostgreSqlDeadLetterCleanupService.cs:20, registered at PostgreSqlBrokerTransport.cs:101-107) is
a PeriodicBackgroundService that, hourly and on one replica, deletes
the host queue's dead_letters rows older than DeadLetterRetentionDays (30 by default,
PostgreSqlTransportSettings.cs:44, :47) in batches and records the remaining depth on the
BrokerMetrics dead-letter depth gauge (PostgreSqlDeadLetterCleanupService.cs:8-18). Its own keys bind from MessageBus:PostgreSql
into PostgreSqlTransportSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlTransportSettings.cs:8,
:11): a Schema and Role that both default to transport (PostgreSqlTransportSettings.cs:14,
:38-42) and MigrateOnStartup, on by default (:36), which a host whose database user cannot create
a role and a schema turns off, creating the schema out of band with the same idempotent DDL
(:30-35). When an INpgsqlDataSourceConfigurator is registered (an RDS, Cloud SQL or Entra token
provider), the transport runs on the same shared NpgsqlDataSource the PostgreSQL contexts use for
that connection string, the startup migration included (PostgreSqlBrokerTransport.cs:33-37,
:103-109). [Rubric §7, Microservices Readiness] and [Rubric §2, Design Patterns] are the lenses:
the broker is a strategy chosen by configuration, behind one contract, with the vendor code outside the
core (ADR-066,
ADR-118).
Assembly anchors
Several pieces of machinery need a Type whose Assembly identifies a layer: the framework's own
AddAssignableTypes assembly scans (MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:59), FluentValidation's AddValidatorsFromAssemblyContaining<T>(), and
the architecture rules' per-package anchor. That is what the AssemblyReference /
ClassReference pairs are, one per layer (Application, Infrastructure),
each a trivial static class AssemblyReference holding Assembly / AssemblyName statics
(MMCA.Common/Source/Core/MMCA.Common.Application/AssemblyReference.cs:5-9) beside a non-static class ClassReference (AssemblyReference.cs:11) for the places a generic constraint forbids a static type.
AddApplication uses the Application pair for the common validators
(MMCA.Common.Application/DependencyInjection.cs:70) and AddInfrastructure uses the Infrastructure
pair to scan entity configurations (MMCA.Common.Infrastructure/DependencyInjection.cs:141-145). They
are deliberately behavior-free; their whole job is to name an assembly for the scanning and
governance tooling. A related, test-only assembly anchor lives in
CreateMigrationProofTable
(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests.MigrationsFixture/CreateMigrationProofTable.cs:24):
a real EF migration for the framework's one SQLite context kept in its own tiny library, because EF
selects migrations by the [DbContext] they carry and a migration compiled into the test assembly
would make every test that names that assembly see a pending migration
(CreateMigrationProofTable.cs:11-21).
Configuration binding, the Settings family
Everything a host operator tunes arrives as a strongly-typed settings object bound from an
appsettings.json section, each carrying a static readonly string SectionName so the section name
lives next to the shape it binds. The pattern in AddInfrastructure is uniform:
services.AddOptions<T>().Bind(configuration.GetSection(T.SectionName)).ValidateDataAnnotations().ValidateOnStart()
(for example ConnectionStringSettings at
MMCA.Common.Infrastructure/DependencyInjection.cs:74-77), so misconfiguration fails fast at
startup rather than lazily on first use
(ADR-070). There are
no ISettings facade interfaces over these types: consumers take IOptions<T> (or the concrete
singleton, for the two dictionary-shaped ones) directly. [Rubric §13, Observability & Operability]
and [Rubric §15, Best Practices] apply: ValidateOnStart plus DataAnnotations ranges (for example
OutboxSettings BatchSize is [Range(1, 1000)] with a default of 50,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxSettings.cs:15-17) turn a config
typo into an immediate, descriptive boot failure.
The Application-layer settings drive composition itself. ApplicationSettings
(MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ApplicationSettings.cs:8) carries
UseMiniProfiler, MaxPageSize (default 500), MaxExportRows ([Range(1, 10_000_000)], default
100,000) and DatabaseInitStrategy (default "Migrate", ApplicationSettings.cs:14-46), and is
passed by value into every IModule.Register. ModulesSettings is a
Dictionary<string, ModuleSettings> bound from the "Modules" section
(MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ModulesSettings.cs:8-11) whose
IsModuleEnabled and IsDependencyRemote helpers (ModulesSettings.cs:29-43) the loader queries;
note that a module absent from configuration is treated as disabled (ModulesSettings.cs:30).
ModuleSettings carries the per-module Enabled flag (default true,
MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ModuleSettings.cs:9) and the
RemoteDependencies list (ModuleSettings.cs:37) that flips a dependency from "in-process" to
"satisfied by an extracted service", with a worked monolith-after-extraction config example on the
property itself (ModuleSettings.cs:24-35). One more Application-layer settings class exists for a
layering reason rather than a composition one: QueryCachePipelineSettings
(MMCA.Common/Source/Core/MMCA.Common.Application/Settings/QueryCachePipelineSettings.cs:20) exposes
the single Cache:PopulateLockTimeout knob the caching query decorator needs, because that decorator
lives in Application and Application cannot reference Infrastructure where
CacheSettings binds the rest of the same section
(QueryCachePipelineSettings.cs:4-18,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheSettings.cs:19-23); AddCaching
binds both from the same section so they cannot drift
(MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:53-61).
The Infrastructure settings cover the rest of the platform. AddInfrastructure binds them here even
though several belong to other chapters by subject (persistence in
group 07, auth in group 08, caching in
group 09, the outbox in group 04): the binding
discipline is this chapter's, the types are theirs. Starting with the database ones,
ConnectionStringSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/ConnectionStringSettings.cs:12) has no
required property at all: SQL Server is the default engine, but a host may run entirely on SQLite or
Cosmos, and may declare its databases through the DataSources section instead
(ConnectionStringSettings.cs:3-11). What is required is that the host can reach some database, and
that rule spans two sections, so it cannot be a data annotation:
ConnectionStringSettingsValidator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/ConnectionStringSettingsValidator.cs:30)
is registered as an IValidateOptions<ConnectionStringSettings> via TryAddEnumerable
(MMCA.Common.Infrastructure/DependencyInjection.cs:84-85) and passes only when the top-level section
names a database on any engine or one DataSources entry does
(ConnectionStringSettingsValidator.cs:47-53, :56-72), failing with a message that lists both shapes
because which one is missing depends on whether the host is a single-database monolith or a
database-per-module one (ConnectionStringSettingsValidator.cs:38-45).
DataSourcesSettings with its per-entry
DataSourceEntrySettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceEntrySettings.cs:19) is the
logical-to-physical source map for database-per-service, built directly from
Get<Dictionary<...>> rather than through the options pipeline
(MMCA.Common.Infrastructure/DependencyInjection.cs:87-91) because a root-level dictionary section
does not bind that way, with a constructor that rejects an empty or reserved "Default" key
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourcesSettings.cs:27-40).
The rest of the platform sections follow the same discipline: MessageBusSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:13), whose
Provider is a plain string defaulting to MessageBusProviders.InProcess
(MessageBusSettings.cs:25) rather than an enum, because any value beyond the three built-in names
selects a transport an adapter package registers (the boundary is described in its own section
below). The same Provider resolves the inbox and outbox postures, both on for any broker unless
set explicitly: the inbox is always off for InProcess, whatever EnableInbox says
(MessageBusSettings.cs:148), while the outbox is off for InProcess unless EnableOutbox turns it
on (MessageBusSettings.cs:186). AddBrokerMessaging
short-circuits entirely for InProcess
(MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:72-75) and otherwise Replaces both
IMessageBus and
IEventBus with their broker-backed counterparts
(DependencyInjection.Messaging.cs:128, :125,
ADR-066);
OutboxSettings (batch size, retries, polling and processing intervals, lease,
retention) consumed by the OutboxProcessor;
PersistenceSettings, whose single CommandTimeoutSeconds defaults to the 30
seconds the framework applied implicitly before the section existed
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/PersistenceSettings.cs:21-22); the
JWT/JWKS group (JwtSettings, the
JwtSigningAlgorithm enum
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:23), and
JwksSettings, whose Enabled defaults to false so an HMAC-only deployment does
not start advertising an RSA key set by accident,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:35-38); and the delivery
channels, SmtpSettings and
PushNotificationSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:8,
section PushNotifications, with the hub path defaulting to /hubs/notifications and a
MaxConnectionsPerUser of 20, PushNotificationSettings.cs:11, :25, :50), bound with
ValidateOnStart by AddPushNotifications
(MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:64-67). OS-level push
(ADR-044) and managed file
storage (ADR-045)
have no settings type and no implementation in the core packages at all, because the core is
cloud-neutral: AddServices registers a null-object default behind each contract,
NullNativePushSender and
NullPushDeviceRegistrar (DependencyInjection.cs:425-426) and
NullFileStorageService (DependencyInjection.cs:433), each through
TryAdd, and a vendor adapter package (MMCA.Common.Azure, MMCA.Common.Aws or MMCA.Common.Gcp)
replaces it when its own section is enabled and complete (DependencyInjection.cs:421-424,
:415-417; the adapters are in group 28). Image
normalization is deliberately not a framework service: decoding needs a native image library every
consumer of the package would otherwise carry (DependencyInjection.cs:430-432). Application code
therefore always resolves something. What the core does keep is the vendor-free half of push,
NativePushPayloads
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/NativePushPayloads.cs:13),
pure System.Text.Json builders for the FCM v1 message and the APNs alert (NativePushPayloads.cs:20,
:42) that the Notification Hubs and SNS adapters send, while the FCM adapter maps the same fields
onto FirebaseAdmin's typed message, so one notification looks the same whichever cloud delivered it
(NativePushPayloads.cs:5-12). [Rubric §2, Design Patterns] again: a null object, not a nullable
dependency. AddPushNotifications does not share that adapter shape: it always adds SignalR, adds the
Redis backplane when a redis connection string is present, replaces the in-app notification
sender and live-channel publisher with their SignalR-backed implementations, and Replaces
SignalR's default user-id provider with the claim-based one, because AddSignalR has already
registered its own and a TryAdd would never take effect
(DependencyInjection.Notifications.cs:45-67).
A null-object default is right for a host that never switched a channel on and wrong for one that did,
so AddInfrastructure closes the gap with a startup tripwire.
CloudAdapterTripwire
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwire.cs:32) is an
IValidateOptions over the empty
CloudAdapterTripwireOptions
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwireOptions.cs:8),
a type whose only job is to ride ValidateOnStart so the check runs with the other startup validators
before any hosted service starts (CloudAdapterTripwireOptions.cs:3-7). When NativePush:Enabled is
true (CloudAdapterTripwire.cs:35) and INativePushSender still resolves, in a scope, to
NullNativePushSender, the host fails with a message naming each adapter package, its registration
call and the keys it needs (CloudAdapterTripwire.cs:62-82); otherwise a deployment that lost the
adapter call would start, pass its health checks and silently drop every push
(CloudAdapterTripwire.cs:16-22). File storage is deliberately not checked, because a FileStorage
section is routinely shared configuration and so does not declare intent, and a host that does store
files without an adapter is not silent anyway: NullFileStorageService fails every upload with
FileStorage.NotConfigured (CloudAdapterTripwire.cs:24-29). Beside it,
StartupConfigurationSummaryService
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/StartupConfigurationSummaryService.cs:35)
is an IHostedService that writes one Information line at start naming the posture the host actually
resolved: the MMCA.Common version stamped on the assembly at build time, the release tag or 0.0.0-dev (StartupConfigurationSummaryService.cs:49-52),
the configured database engines, the bus provider with its EnableDelayedRedelivery value, the cache
mode and the tenancy mode (StartupConfigurationSummaryService.cs:55-74). It logs names and flags
only, deriving the engines from whether a connection string is set and never from its text
(StartupConfigurationSummaryService.cs:20-23), and it names the cache tier without resolving
ICacheService, so a Redis-backed host does not open its connection at startup (:93-104). It also
emits the one Warning a RabbitMQ host with delayed redelivery off needs, because a handler failure
that outlasts the in-process retries then dead-letters instead of being rescheduled
(StartupConfigurationSummaryService.cs:82-85, :25-30). [Rubric §13, Observability & Operability]
covers both: "which version, which bus, which cache?" is answered by the first lines of the log. One
binding is deliberately
elsewhere: JwtSettings is bound by the API layer's AddCommonAuthentication
(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:144-145),
so a host that skips authentication never pays for a JWT section it does not have.
The three opt-in feature sections follow the same shape with one extra rule worth reading closely.
SchedulerSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/SchedulerSettings.cs:16) and
AuditTrailSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSettings.cs:16) each make
Enabled (default false) the single gate over both the behavior and whether the backing table is
mapped into the model at all (SchedulerSettings.cs:10-14, AuditTrailSettings.cs:10-15), so a host
that never opts in keeps exactly the migrations it had. Their tunables are ranged the same way
(PollingIntervalSeconds default 30 and LeaseSeconds default 300, SchedulerSettings.cs:28-46;
RetentionDays default 90, AuditTrailSettings.cs:37-38), and per-job retiming lives in
ScheduledJobOverrideSettings bound from Scheduler:Jobs:{Name}
(SchedulerSettings.cs:63, :66-74). TenancySettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:47) adds the
collection-binding subtlety: ResolutionOrder and ExcludedPathPrefixes bind as empty lists and the
framework reads EffectiveResolutionOrder / EffectiveExcludedPathPrefixes instead
(TenancySettings.cs:79, :106), because the configuration binder ADDS to a pre-populated collection
rather than replacing it, so a non-empty default would leave a host running the framework's entries as
well (TenancySettings.cs:38-45). Its per-tenant database routing is pure configuration:
TenantEntrySettings (TenancySettings.cs:135) keys
TenantDataSourceOverrideSettings (TenancySettings.cs:152) by
physical data source name, and TenancySettingsValidator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:25) fails
the boot when an override names a source that does not exist, when it declares no connection string at
all, or when the resolution order names TenantResolutionStrategy Header
without TrustTenantHeader set (TenancySettingsValidator.cs:75-82, TenancySettings.cs:103-110), or
names a strategy that is not defined (TenancySettingsValidator.cs:89). Every one of those failures is a
misconfiguration that would otherwise surface as silent cross-tenant behavior, which is exactly the bug
class tenancy exists to prevent, so it is worth a failed boot. [Rubric §11, Security] is the category
there.
Two composition questions are answered by a small resolver rather than by a settings property,
because a bound property cannot distinguish "configured false" from "never configured" and the safe
answer differs by environment. ApplicationNamespace
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/ApplicationNamespace.cs:35) is the
one name every piece of shared infrastructure is namespaced by: Redis cache keys, distributed-lock
keys, distributed rate-limit counter keys, the Redis output-cache InstanceName, the SignalR Redis
backplane channel prefix and the broker's endpoint prefix (ApplicationNamespace.cs:7-12). It
resolves the explicit Application:Namespace key when set (:32, :54-60), otherwise the host's
application name, otherwise the "app" fallback (:35), and sanitizes the result to characters that
are safe in a Redis key, a channel name and a queue name (:43-44). Composition reads it where the
shared resource is wired: AddPushNotifications for the backplane channel prefix
(MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:80), AddBrokerMessaging for the
endpoint prefix when MessageBus:EndpointPrefix is blank (DependencyInjection.Messaging.cs:100-102),
and the cache-key builder
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheKeyPrefix.cs:126). The default is
per-application rather than empty because two hosts pointed at one Redis or one broker otherwise share
every keyspace, and NotificationHub ships in the framework, so its backplane channel name is
identical in every consumer and a user-targeted push in one application reaches the other
application's clients holding the same numeric user id (ApplicationNamespace.cs:15-26).
SmtpTransportSecurity
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Mail/SmtpTransportSecurity.cs:26) has the same
three-step shape for TLS: the explicit Smtp:EnableSsl key, then configuration, then secure unless
the host says it is Development (SmtpTransportSecurity.cs:29, :37-49). SmtpEmailSender resolves
it once at construction (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Mail/SmtpEmailSender.cs:36)
through the overload that also logs one startup warning when a non-Development host turned TLS off for
a configured relay, so that decision is visible in the logs of the deployment that made it
(SmtpTransportSecurity.cs:51-58). Development keeps the permissive default because local development
targets MailDev, which offers no TLS (SmtpTransportSecurity.cs:21-25). [Rubric §11, Security]
covers both: the secure value is the one you get by configuring nothing.
The two routing attributes
Two attributes, both in MMCA.Common.Infrastructure, both Inherited = true so they ride down a
configuration class hierarchy, encode where an entity is stored declaratively: the per-entity half of
the database-per-service strategy
(ADR-006).
UseDataSourceAttribute
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/UseDataSourceAttribute.cs:13-18) names the
engine (DataSource: SQL Server, PostgreSQL, Cosmos or SQLite)
and is carried by the provider-specific configuration base classes, so choosing a base class chooses
the engine with no change to the entity (see
primer §2).
UseDatabaseAttribute
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/UseDatabaseAttribute.cs:21-26) names the
logical database on that engine; its documented resolution order (UseDatabaseAttribute.cs:9-14)
is the attribute value, then the module name derived from the entity's namespace (the segment before
Domain), then "Default". The persistence runtime
(EntityDataSourceRegistry,
DataSourceResolver,
DbContextFactory) reads these attributes up front
to map each entity to a physical source; those types are documented in the persistence chapter, but the
markers that feed them live here because they are part of how a module declares its composition.
Shared user use-case bases: composition in the other direction
The chapter's last family is composition at the handler level rather than the container level. ADC
and Store each own an Identity module, and thirteen of their account use cases had drifted into
line-identical copies (or would have), so the workflow was hoisted into abstract bases that each app
subclasses:
ChangePasswordHandlerBase<TUser, TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:55,
ADR-032),
ChangePreferencesHandlerBase<TUser, TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:23),
GetUserPreferencesHandlerBase<TUser>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandlerBase.cs:19),
DeleteUserHandlerBase<TUser, TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:95),
the erasure workflow behind
ADR-005,
ExportUserDataHandlerBase<TUser, TQuery>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:61),
the data-subject access workflow, and the password-recovery pair
ForgotPasswordHandlerBase<TUser, TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:63)
and ResetPasswordHandlerBase<TUser, TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:42),
which run the token issue-and-redeem flow described in
ADR-091 and collapse every
rejection to one Auth.InvalidResetToken error so the endpoint reveals nothing about which addresses
hold accounts (ResetPasswordHandlerBase.cs:20-22). Both password-writing bases also revoke every
live refresh session on the account, so a stolen refresh chain cannot outlive the remediation the
user just performed, and both persist that revocation before the password save, so a revoke
failure throws while the password is still unchanged and the user simply retries
(ChangePasswordHandlerBase.cs:43-45, :122-129; ResetPasswordHandlerBase.cs:36-39, :100-108,
where the revoke also stands when the aggregate then rejects the new password;
ADR-097). The
change-password base also throttles a wrong current password through its own
password-change:{userId} failed-attempt counter, keyed apart from sign-in so that lockout never
locks the owner out of signing in (ChangePasswordHandlerBase.cs:47-52). The two email-sending bases
compose their messages through UserEmailResources
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/Emails/UserEmailResources.cs:15), which reads
its .resx siblings through a plain ResourceManager because the Application layer references no
Microsoft.Extensions.Localization (UserEmailResources.cs:8-14,
ADR-027). InRecipientCulture
runs the composition under the recipient's stored PreferredCulture, resolved to the closest
supported culture, and puts the request's culture back afterwards (UserEmailResources.cs:29-45);
Get throws on a missing key rather than sending a blank line (:50-52), and Plural picks the
.One / .Other form the UI resources use (:64-65). The call sites are
ForgotPasswordHandlerBase.cs:133 and SendEmailConfirmationHandlerBase.cs:143, and the subject stays a
protected virtual hook an app can override (ForgotPasswordHandlerBase.cs:148,
SendEmailConfirmationHandlerBase.cs:168).
Six more bases cover the account-security workflows a host opts into with
AddTwoFactorAuthentication (MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:48) and
AddEmailConfirmation (:68). The two-factor four are a deliberate two-step enrollment:
BeginTwoFactorEnrollmentHandlerBase<TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/BeginTwoFactorEnrollmentHandlerBase.cs:41)
mints a secret and stores it without activating the factor, so an authenticator that was never
really keyed cannot lock the owner out, and re-running it on an enrolled account fails rather than
silently re-keying a live secret (BeginTwoFactorEnrollmentHandlerBase.cs:14-25);
ConfirmTwoFactorEnrollmentHandlerBase<TCommand>
(ConfirmTwoFactorEnrollmentHandlerBase.cs:39) verifies a time-based code (a recovery code cannot
confirm an enrollment, because the step exists to prove the app holds the secret) and generates the
first recovery-code set in the same call that activates the factor, so an account is never in the
state "second factor on, no way back in" (ConfirmTwoFactorEnrollmentHandlerBase.cs:15-24);
DisableTwoFactorHandlerBase<TCommand>
(DisableTwoFactorHandlerBase.cs:36) demands a live factor to turn the factor off, because
otherwise whoever holds a stolen access token can strip the control that would have stopped them, and
here a recovery code is accepted since a user who lost the device is exactly who needs it
(DisableTwoFactorHandlerBase.cs:14-24); and
RegenerateRecoveryCodesHandlerBase<TCommand>
(RegenerateRecoveryCodesHandlerBase.cs:36) replaces the whole set rather than appending to it, so a
list the user believes is copied stops working (RegenerateRecoveryCodesHandlerBase.cs:15-24). The
three bases that check a code after sign-in (confirm, disable, regenerate) share one per-account
failed-attempt budget, keyed by TwoFactorAttemptKey
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/TwoFactorAttemptKey.cs:15)
as two-factor:{userId} (TwoFactorAttemptKey.cs:20-21), so a wrong code on any of them counts
against the same lockout, while staying separate from the email-keyed sign-in counter and the
change-password one so a lockout here cannot lock the owner out of signing in
(TwoFactorAttemptKey.cs:5-14; used at ConfirmTwoFactorEnrollmentHandlerBase.cs:75,
DisableTwoFactorHandlerBase.cs:54, RegenerateRecoveryCodesHandlerBase.cs:57). The
email-confirmation pair mirrors the password-recovery pair's privacy rule:
SendEmailConfirmationHandlerBase<TUser, TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/SendEmailConfirmationHandlerBase.cs:64)
answers the inline dispatch with success for every address, because that dispatch only writes one
queue row and never looks the address up, so neither the response nor its timing carries a signal
about which addresses hold accounts (SendEmailConfirmationHandlerBase.cs:27-32, :91-101), and
ConfirmEmailHandlerBase<TUser, TCommand>
(ConfirmEmailHandlerBase.cs:63) collapses every rejection to one
Authentication.InvalidConfirmationToken error and consumes the token before the save, matching
ResetPasswordHandlerBase, because leaving it live until the write succeeds opens a replay window
(ConfirmEmailHandlerBase.cs:19-50). Like the other bases these take the app's command record as a
type parameter and read it only through this group's small contracts, and the aggregate constraint is
the capability the workflow needs rather than a concrete type (IEmailConfirmableUser on
ConfirmEmailHandlerBase.cs:69). Inside it a private AccountProof enum
(ConfirmEmailHandlerBase.cs:73) records how the caller proved the account on a completing request:
no password credential exists so the token is the whole proof, the caller is signed in as the
account, the caller supplied the current password, or the caller claimed the account with a new
password (ConfirmEmailHandlerBase.cs:72-85).
Each base is generic in the app's User aggregate and in the app's own command or query record, and
reads that record only through the small contracts in this group:
IUserScopedRequest (UserId,
MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserScopedRequest.cs:8),
IUserScopedCommand<out TRequest> (adds the embedded payload,
IUserScopedCommand.cs:14), and IUserOwnedRequest (adds CurrentUserId and
CurrentUserRole, IUserOwnedRequest.cs:8). The commands stay app-side precisely because the two apps
disagree on their pipeline attributes: ADC marks the password-change command ICacheInvalidating and
Store does not (ChangePasswordHandlerBase.cs:18-37). Note that
IUserScopedCommand<out TRequest> is deliberately not
ICommandWithRequest<TRequest>: implementing the latter also opts a command into automatic
CommandRequestValidator registration, which is a per-app decision, so implementing this one alone
changes no pipeline behavior (IUserScopedCommand.cs:6-12). That choice has a consequence the
framework answers with a shared validator:
ChangePreferencesCommandValidatorBase<TCommand>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommandValidatorBase.cs:29)
is a command validator, because a validator over the request record would never run for a command
that carries its payload through IUserScopedCommand, and it is abstract because module scanning
registers validators from the app assemblies only, so each app declares a one-line sealed subclass
(ChangePreferencesCommandValidatorBase.cs:14-20). It requires the request and rejects an unsupported
culture or a theme other than light or dark, while a null field passes as "leave unchanged"
(ChangePreferencesCommandValidatorBase.cs:42-60, :8-13), and it reads the accepted values from the
same definitions the aggregate enforces, so the rejection moves in front of the handler without a
second definition of what is valid (:22-27).
The export base is the most instructive of the thirteen, because it is where the container-level and
handler-level composition meet. It authorizes through
UserOwnershipRule.CheckOwnership
(ExportUserDataHandlerBase.cs:100-109), reads the account through GetReadRepository
(ExportUserDataHandlerBase.cs:111-112), asks the subclass for the app-specific subject snapshot
(:119), and then fans out sequentially over every injected
IUserDataExportSection (:121-127), sequential on purpose because the
sections share one scoped DbContext and because registration order is the published order of the
document. A section that throws degrades to an envelope reporting Available = false rather than
failing the export, which is the contract
UserDataExportSectionResult encodes with its Complete /
Unavailable factories
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/IUserDataExportSection.cs:73,
:91), with the caller-safe default text in
UserDataExportSectionDefaults (IUserDataExportSection.cs:105-113).
The result is a UserDataExportDTO that is PII by design and is
therefore never logged or cached (ExportUserDataHandlerBase.cs:55-56).
Around those bases sit the small shared pieces: UserOwnershipRule
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserOwnershipRule.cs:20), the
owner-or-privileged-role decision returning a Forbidden
Error or null (UserOwnershipRule.cs:37) with the
privileged-role test passed in already evaluated because each app owns its own role vocabulary
(UserOwnershipRule.cs:14-18), while each base is itself a partial class that declares its own
[LoggerMessage] audit lines (for example ChangePasswordHandlerBase.cs:147);
SoftDeletedUserValidator<TUser>
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/SoftDeletedUserValidator.cs:20), which answers
ISoftDeletedUserValidator with one
query-filter-bypassing existence check (SoftDeletedUserValidator.cs:31-34); and
GetUserPreferencesQuery
(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesQuery.cs:5),
the one request record that was byte-identical in both apps and so became shared. [Rubric §34, Architecture Governance & Documentation] and [Rubric §1, SOLID] are the categories here: the variation points are explicit
generic parameters and protected virtual hooks, so an app extends behavior without forking the
workflow.
End-to-end: one host's boot
Reading MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs top to bottom shows the whole
chapter cooperating. The host calls AddInfrastructure(builder.Configuration) (Program.cs:356), opts
into the scheduler and the audit trail (Program.cs:360, :350), then calls AddModuleHost with the
single assembly that declares ConferenceModule and a Serilog-backed
ModuleLoader logger (Program.cs:381-384), and passes the resulting
ModulesSettings to AddAPI (Program.cs:386). The whole handler-contributing
sequence then goes inside one AddMmcaApplicationPipeline call (Program.cs:418-424): step one is
moduleHost.RegisterModules (module discovery), step two replaces the disabled Engagement stub with a
real gRPC client (AddEngagementBookmarkCountClient()), and step three is AddBrokerMessaging with
its integration-event consumers, so MessageBusSettings Provider decides
whether IMessageBus stays the default
InProcessMessageBus
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:414) or is replaced by the
framework's own BrokerMessageBus over the
IBrokerTransport registered for that provider name
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:72-75, :84,
:119). Because this is the Conference service, only the Conference module is
Enabled in its configuration; every other discovered module takes the RegisterDisabledStubs path.
The pipeline call closes with AddApplicationDecorators() and seals the collection, so the decorators
wrap the now-registered Conference handlers and any later handler registration throws rather than
running bare. Afterwards the host adds module health checks from the loader (Program.cs:447) and
finally app.Services.InitializeDatabaseAsync(moduleHost.ApplicationSettings, moduleHost.ModuleLoader)
(Program.cs:460) applies migrations and runs the module seeders the loader collected. The exact same
module assemblies, dropped into a monolith host with every module Enabled, would Kahn-sort into one
in-process graph with no gRPC clients, which is precisely the reversibility
ADR-008 is after.
AssemblyReference
MMCA.Common.Application ·
MMCA.Common.Application·MMCA.Common/Source/Core/MMCA.Common.Application/AssemblyReference.cs:5· Level 0 · class (static)
What it is: a tiny static class exposing the assembly that contains it plus that assembly's simple name, for use as a stable anchor when something needs to say "scan the assembly this type lives in." This section covers the Application-layer copy; the framework ships a near-identical copy in every layer package, and the copies that belong to other groups get their own sections there.
Depends on:
System.Reflection.Assembly(BCL) only. No first-party dependencies, and that purity is why it sits at Level 0.Concept introduced, assembly-marker types for convention scanning.
[Rubric §2, Design Patterns]assesses whether recurring problems are solved with recognised patterns; the marker (or anchor) type is the idiomatic way to hand anAssemblyto a scanner without coupling to an incidental concrete class.[Rubric §1, SOLID](DIP): registration code depends on a deliberate, meaningless token rather than ontypeof(SomeRandomHandler).Assembly, so renaming or moving any real type never breaks the scan. Repeating the identicalAssemblyReferenceplusClassReferencepair in every package keeps each assembly self-describing with no cross-layer reference at all.Walkthrough: two
public static readonlyfields resolved once at type initialization.Assemblyistypeof(AssemblyReference).Assembly(MMCA.Common/Source/Core/MMCA.Common.Application/AssemblyReference.cs:7);AssemblyNameisAssembly.GetName().Namewith a?? string.Emptynull-coalescing fallback (AssemblyReference.cs:8), so the field is never null even if the runtime reports no simple name. The Application copy carries no XML doc, and neither does the one other Core copy, in Infrastructure, which is identical apart from its namespace (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/AssemblyReference.cs:5-8).Why it's built this way: a purpose-built anchor decouples scanning from any business type, and one per package means an assembly can be named without referencing anything inside it. The per-module Application assemblies follow the same convention (see the module copies in group-22 and group-24).
Where it's used: as the assembly source for Scrutor scans and FluentValidation discovery, usually through its non-static companion (next section) because those helpers are generic.
Caveats / not-in-source: the architecture-fitness map does not route through
AssemblyReferencefor this layer.CommonArchitectureMappins one anchor type per package, and for six of the seven mapped layers that anchor is a real type (Result,BaseEntity<>,DomainEventDispatcher,ApplicationDbContext,ApiControllerBase,ResultGrpcExtensions); only the UI layer uses a dedicated marker,UISharedAssemblyReference(MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/CommonArchitectureMap.cs:21-27).
ClassReference
MMCA.Common.Application ·
MMCA.Common.Application·MMCA.Common/Source/Core/MMCA.Common.Application/AssemblyReference.cs:11· Level 0 · class
What it is: the non-static companion to
AssemblyReference: an empty, instantiable class used wherever a generic type parameter needs an assembly anchor and a static class will not satisfy the constraint.Depends on: nothing first-party; nothing from the BCL beyond
object.Concept: the companion half of the marker pattern introduced under
AssemblyReference. C# static classes cannot be used as generic type arguments, and the registration helpers that take a marker are constrained to an instantiable reference type:ScanModuleApplicationServices<TAssemblyMarker>()declareswhere TAssemblyMarker : class(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:246-247) and so doesMmcaApplicationPipelineBuilder.ScanModule<TAssemblyMarker>()(MmcaApplicationPipelineBuilder.cs:27-28).ClassReferencefills that slot without weakeningAssemblyReference's static-ness.[Rubric §33, Developer Experience]assesses how conventional the inner loop is: one token (ScanModuleApplicationServices<ClassReference>()) is the entire registration ceremony a new module needs.Walkthrough: a single body-less type declaration,
public class ClassReference;(MMCA.Common/Source/Core/MMCA.Common.Application/AssemblyReference.cs:11). No members. Its only meaningful property is the assembly it belongs to, read by the scanner throughtypeof(TAssemblyMarker).Assembly(DependencyInjection.ModuleScanning.cs:31) before it hands thatAssemblyto the assembly-typed overload. The Infrastructure copy declares the same undocumented, body-less type (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/AssemblyReference.cs:11).Why it's built this way: keeping a separate non-static anchor sidesteps the static-class generic-argument restriction while leaving
AssemblyReferencestatic (and therefore impossible to instantiate accidentally). Every module's Application assembly defines its ownClassReference, so each module scans itself by passing its local copy.Where it's used: as the
TAssemblyMarkerargument inScanModuleApplicationServices<TAssemblyMarker>(). All three ADC module composition roots callservices.ScanModuleApplicationServices<ClassReference>()with their own local copy (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/DependencyInjection.cs:141,MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/DependencyInjection.cs:92), as do Store's three (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/DependencyInjection.cs:53,.../Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:51,.../Sales/MMCA.Store.Sales.Application/DependencyInjection.cs:65) and Helpdesk's single module (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/DependencyInjection.cs:34). The framework rootAddApplication()passes the Application-layer copy toAddValidatorsFromAssemblyContaining<ClassReference>()(DependencyInjection.cs:70).
DecoratorPipelineSeal
MMCA.Common.Application ·
MMCA.Common.Application·MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:368· Level 0 · class (private, sealed)
What it is: a private, empty marker class that
DependencyInjectionregisters into the service collection as a singleton instance the momentAddApplicationDecorators()finishes. Its presence in the descriptor list is the record that the CQRS decorator pipeline has been closed on that collection. It is never resolved and never depended on: its only job is to be there.Depends on: nothing. It has no members and no base type beyond
object.Concept introduced, an ordering invariant enforced by a marker registration. The framework's one hard composition rule is that
AddApplicationDecorators()must run after every handler registration, because Scrutor'sTryDecoratecan only wrap registrations that already exist (seeDependencyInjectionfor the full pipeline). A handler registered afterwards resolves completely unwrapped: no feature gate, no authorization, no validation, no timeout, no transaction, and nothing fails at startup to say so.[Rubric §15, Best Practices & Code Quality]assesses whether a rule that has to be obeyed is enforceable rather than merely documented: instead of leaving the ordering as a comment, the framework leaves a token in the container and has every handler-contributing entry point check for it first.[Rubric §15, Best Practices and Code Quality]: making the markerprivatemeans no consumer can register, resolve, or fake it, so the signal cannot be forged from outside.[Rubric §14, Testability]: the same marker is whatVerifyDecoratorPipeline()reads to tell "no handler is wrapped" apart from "some handler is not wrapped", which are two different failures with two different messages.Walkthrough
- Declaration:
private sealed class DecoratorPipelineSeal;(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:368), sitting outside theextension(IServiceCollection)block beside the three private helpers that use it, with its role written into the XML doc (:363-367). SealPipeline(:712-713): a one-lineservices.TryAddSingleton(new DecoratorPipelineSeal()). Registering an instance rather than a type means nothing is ever constructed lazily, andTryAddmeans a second call is a no-op at the descriptor level. It is called at the very end ofAddApplicationDecorators(), after all thirteenTryDecoratecalls (:145).IsPipelineSealed(:701-710): a linear scan of the collection comparingdescriptor.ServiceTypetotypeof(DecoratorPipelineSeal). No provider is built, so the check is safe to run mid-composition and costs one pass over the descriptor list.ThrowIfPipelineSealed(:715-725): the guard itself. When the marker is present it throws anInvalidOperationExceptionnaming the offending call and spelling out both remedies, move the call ahead ofAddApplicationDecorators()or compose the whole sequence withAddMmcaApplicationPipeline(...)(:719-723). Every entry point that can contribute a handler opens with it:AddApplicationDecoratorsitself (:117, which is what makes a second call throw),ScanModuleApplicationServices(:182),AddEntityCrud(:335),AddEntityUpdateVerb(:397),AddEntityUpdate(:448) andAddMmcaApplicationPipeline(:614).- The two deliberate non-guards:
AddCommandRequestValidator<TCommand, TRequest>()(:475) andAddApplicationProfiling()(:565) do not check the marker. A validator is not a handler, and the profiling pair is an outer decoration that is supposed to be applied on top of the closed pipeline;ApplicationPipelineCompositionTestspins that second case as allowed behavior (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/ApplicationPipelineCompositionTests.cs:139-144). - Read by
VerifyDecoratorPipeline()(:649-656): before inspecting any handler descriptor it asksIsPipelineSealed, and when the answer is no it throws the distinct "the pipeline was never closed" message rather than listing every handler as undecorated.
- Declaration:
Why it's built this way: a marker in the collection is the only piece of state that travels with an
IServiceCollection, which is what the guard needs, because the ordering rule is a property of that collection and not of the process. Registering it as an instance keeps the check allocation-free at resolution time (nothing ever resolves it) and keeps it invisible to consumers, which is why it isprivaterather thaninternal.Where it's used: only inside
DependencyInjection.cs, by the four helpers above. Its observable effects are the exception messages tested inApplicationPipelineCompositionTests(:114-131,:182-188).Caveats / not-in-source: the seal records that the decorators ran, not that they ran correctly. A host that registers a handler after
AddApplicationDecorators()through a path with no guard, for example a bareservices.AddScoped<ICommandHandler<...>, ...>(), still slips through; catching that is exactly whatVerifyDecoratorPipeline()exists for, and it has to be called explicitly by a fitness test.
MmcaApplicationPipelineBuilder
MMCA.Common.Application ·
MMCA.Common.Application·MMCA.Common/Source/Core/MMCA.Common.Application/MmcaApplicationPipelineBuilder.cs:12· Level 0 · class (sealed)
What it is: the small builder handed to the callback of
AddMmcaApplicationPipeline(...). It collects every registration that has to happen betweenAddApplication()andAddApplicationDecorators(), which is to say everything that puts a command or query handler into the container: module assembly scans, aModuleLoaderrun, cross-service gRPC clients, broker messaging.Depends on:
DependencyInjection(it callsScanModuleApplicationServiceson the collection it holds). Externals:Microsoft.Extensions.DependencyInjection.IServiceCollectionandSystem.Reflection.Assembly.Concept introduced, a builder whose constructor is the guard.
[Rubric §33, Developer Experience]assesses how hard the framework makes it to do the right thing by default. The ordering rule this builder exists to protect is invisible at the call site: a handler registered after the decorators is silently unwrapped. Rather than documenting the order and hoping, the framework makes the only way to obtain a builder be inside the call that also runs the decorators afterwards. The constructor isinternal(MmcaApplicationPipelineBuilder.cs:14), and the XML doc states the reason plainly: "not constructible on its own, because outside that call there is nothing keeping the decorators last" (:9-10).[Rubric §2, Design Patterns]: this is the Builder shape used for scoping rather than for object construction, the same idea as ASP.NET Core's ownIEndpointRouteBuilderstyle callbacks.[Rubric §15, Best Practices & Code Quality]: a host's composition root now reads as one call whose body is a list of steps, so a reviewer can see at a glance whether a registration belongs inside the pipeline.Walkthrough: four members, all trivially thin.
Services(:19), the collection under construction, exposed for a step that needs it directly.ScanModule<TAssemblyMarker>()(:27-32, constrainedwhere TAssemblyMarker : classat:28), which forwards toServices.ScanModuleApplicationServices<TAssemblyMarker>()and returnsthisfor chaining. The marker is typically the module's ownClassReference.ScanModules(params Assembly[] moduleAssemblies)(:41-51), the assembly-typed form for hosts that resolve their module set at runtime rather than naming a marker type per module; it null-guards the array (:43) and loops the assembly overload of the scanner (:45-48).Register(Action<IServiceCollection> register)(:62-68), the escape hatch for an arbitrary step, null-guarded at:64. The doc names exactly what belongs here: aModuleLoader.DiscoverAndRegister(...)call, cross-service gRPC clients, broker messaging, per-host handler overrides (:53-58).
Why it's built this way: the callback shape is what makes the ordering rule structural instead of advisory.
AddMmcaApplicationPipelinerunsAddApplication(), invokes the callback with a freshly constructed builder, and then returnsAddApplicationDecorators()(MMCA.Common.Application/DependencyInjection.cs:284-293), so the decorators are last by construction. Everything that is not a handler registration (infrastructure, API, telemetry, options, health checks) deliberately stays outside the call, because its order relative to the decorators does not matter (MMCA.Common.Application/DependencyInjection.cs:272-273).Where it's used: constructed in exactly one place,
AddMmcaApplicationPipeline(MMCA.Common.Application/DependencyInjection.cs:284). Every ADC and Store service host composes through it, by way of theConfigurePipelinecallback it hands toAddMmcaServiceHost: ADC Conference (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:359-363), Identity (.../MMCA.ADC.Identity.Service/Program.cs:288), Engagement (.../MMCA.ADC.Engagement.Service/Program.cs:278), Notification (.../MMCA.ADC.Notification.Service/Program.cs:215), Store Catalog (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:106-112), Sales (.../MMCA.Store.Sales.Service/Program.cs:234) and Identity (.../MMCA.Store.Identity.Service/Program.cs:211). The architecture fitness tests replay the same shape,MMCA.Store/Tests/Architecture/MMCA.Store.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:52-53andMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/ApplicationPipelineCompositionTests.cs:34.Caveats / not-in-source: the MMCA.Helpdesk host does not use the builder. It writes the three-call sequence by hand (
MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:66,:104,:120) with the ordering rule stated as a comment above it (:65), which is still a supported composition, just the unguarded one.
QueryCachingOptIn
MMCA.Common.Application ·
MMCA.Common.Application·MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:374· Level 0 · class (private, sealed)
What it is: a private, empty marker class that
AddQueryCaching()registers into the service collection as a singleton instance. Its presence records that this host opted into the CQRS query cache, andAddApplicationDecorators()reads it to decide whether the caching decorator pair joins the pipeline. It is the sibling ofDecoratorPipelineSeal, declared directly below it inDependencyInjection.Depends on: nothing. It has no members and no base type beyond
object.Concept introduced, an opt-in carried as a descriptor rather than an options value.
[Rubric §12, Performance & Scalability]assesses whether a host pays only for the caching it uses: the caching pair is off by default, and without the opt-inIQueryCacheableandICacheInvalidatingare inert markers, so a host that never caches query results does not pay a prefix-generation bump and a delayed re-eviction on every write against keys nothing populates (DependencyInjection.cs:208-214). The flag has to be readable during composition, before any provider exists, becauseAddApplicationDecorators()builds the decorator lists from it. A marker descriptor is the one piece of state anIServiceCollectioncarries that a registration method can inspect without building a provider, which is the same reasoning as the seal.[Rubric §15, Best Practices & Code Quality]: making itprivatemeans onlyAddQueryCaching()can set it ("Private for the same reason as the seal",:370-373).Walkthrough
- Declaration:
private sealed class QueryCachingOptIn;(DependencyInjection.cs:374), outside theextension(IServiceCollection)block besideDecoratorPipelineSeal(:368). - Set by
AddQueryCaching()(:223-230): guarded byThrowIfPipelineSealed(:225), so calling it after the decorators ran throws instead of silently doing nothing, thenservices.TryAddSingleton(new QueryCachingOptIn())(:227). An instance plusTryAddmakes a second call a no-op. - Read by
IsQueryCachingEnabled(:376-385): a linear scan comparingdescriptor.ServiceTypetotypeof(QueryCachingOptIn), called once byAddApplicationDecorators()(:165). When true,CachingCommandDecorator<,>is spliced between Logging and Validating in the command list (:174) andCachingQueryDecorator<,>between Logging and Validating in the query list (:186); when false both slots spreadType.EmptyTypesand every other position is unchanged (comment at:162-164).
- Declaration:
Why it's built this way: because the opt-in is a flag the decorator step reads, it must be registered before that step: before
AddMmcaApplicationPipeline(...)or inside its callback aspipeline.Register(s => s.AddQueryCaching())(:216-220). The cache store itself (ICacheService) is a separate registration made by Infrastructure'sAddCaching(:218-220), so the marker switches only the pipeline position, not the cache.Where it's used: only inside
DependencyInjection.cs, byAddQueryCaching()andIsQueryCachingEnabled. Its effect is pinned byQueryCachingOptInTests(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Decorators/QueryCachingOptInTests.cs:75,:87,:106) and the differential replica test (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DependencyInjection/ApplicationPipelineDifferentialTests.cs:35), and the conformance base exposes the matching switchUsesQueryCaching(defaultfalse,MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/DecoratorPipelineOrderTestsBase.cs:56) that a host's pipeline-order test must set to match. ADR-026 is the decision record for the caching strategy.Caveats / not-in-source: no
AddQueryCaching()call was found in ADC or StoreSource/, so in those hosts the caching pair is currently absent from the pipeline. Whether that is the intended production posture for each host is not determinable from source.
DependencyInjection
MMCA.Common.Application ·
MMCA.Common.Application·MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Crud.cs:14· Level 11 · class (static, C#extension(IServiceCollection))
What it is: the composition-root extension class that assembles the framework's entire Application layer into the DI container. The class is
partialand its public members are split across six files, each with its ownextension(...)block:DependencyInjection.cs(class at:31, block at:33:AddApplication(),AddApplicationDecorators(),AddQueryCaching(),AddApplicationProfiling(),AddMmcaApplicationPipeline(configure),VerifyDecoratorPipeline()),DependencyInjection.ModuleScanning.cs(:16,ScanModuleApplicationServices<TAssemblyMarker>()and itsAssemblyoverload),DependencyInjection.Crud.cs(class at:14, block at:16:AddEntityCrud<...>(),AddEntityUpdateVerb<...>(),AddEntityUpdate<...>(),AddCommandRequestValidator<TCommand, TRequest>()),DependencyInjection.Extensibility.cs(:11,AddUserDataExportSection<TSection>(),AddEventUpcaster<TSource, TTarget, TUpcaster>()),DependencyInjection.ProcessManagers.cs(:9,AddProcessManagers()) andDependencyInjection.Webhooks.cs(:15,AddWebhookEvent<TEvent>(eventType), plus a second block overMmcaApplicationPipelineBuilderat:86carryingAddWebhookDelivery()). The private members behind the pipeline stay inDependencyInjection.csbelow the extension block: the two markersDecoratorPipelineSeal(:368) andQueryCachingOptIn(:374), and the helpersIsQueryCachingEnabled(:376),IsPipelineSealed(:387),DecorateInExecutionOrder(:403),SealPipeline(:411),ThrowIfPipelineSealed(:414) andFormatUndecorated(:426).Depends on: the framework's own registration helpers
ServiceCollectionDecoration(TryDecorateWith,AddAssignableTypes) andScanRegistration, a linked internal source (MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:47,:8); the core singletonsIDomainEventDispatcher/DomainEventDispatcher,IEventUpcasterRegistry/EventUpcasterRegistry,INavigationMetadataProvider,IEntityQueryPipeline; the open-generic defaultINavigationPopulator<in TEntity>/NullNavigationPopulator<TEntity>; the scopedISoftDeletedUserMarkerWriterand the erasure'sDeleteUserPushInstallationsInternalCommand/DeleteUserPushInstallationsInternalCommandHandler; the markerClassReference; the permission registryIPermissionRegistry/UnconfiguredPermissionRegistryand the parallel permission catalog fallbackIPermissionCatalog(also defaulted toUnconfiguredPermissionRegistry); the open-generic handler contractsICommandHandler<in TCommand, TResult>andIQueryHandler<in TQuery, TResult>; the eight command decoratorsTransactionalCommandDecorator<TCommand, TResult>,TimeoutCommandDecorator<TCommand, TResult>,ValidatingCommandDecorator<TCommand, TResult>,CachingCommandDecorator<TCommand, TResult>,LoggingCommandDecorator<TCommand, TResult>,AuthorizationCommandDecorator<TCommand, TResult>,FeatureGateCommandDecorator<TCommand, TResult>,ViewAsCommandDecorator<TCommand, TResult>; the six query decoratorsTimeoutQueryDecorator<TQuery, TResult>,ValidatingQueryDecorator<TQuery, TResult>,CachingQueryDecorator<TQuery, TResult>,LoggingQueryDecorator<TQuery, TResult>,AuthorizationQueryDecorator<TQuery, TResult>,FeatureGateQueryDecorator<TQuery, TResult>; the optionalProfilingCommandDecorator<TCommand, TResult>andProfilingQueryDecorator<TQuery, TResult>; the scanned contract familiesIDomainEventHandler<in TDomainEvent>,IIntegrationEventHandler<in TIntegrationEvent>,IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>,IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>,IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType>,IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType>,IEntityUpdateCommandApplier<TEntity, TUpdateRequest, TIdentifierType, in TCommand>; the generic write-side handlersCreateEntityHandler<TCreateRequest, TEntity, TIdentifierType, TEntityDTO>,UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>,UpdateEntityCommandHandler<TCommand, TEntity, TEntityDTO, TIdentifierType, TUpdateRequest>andDeleteEntityHandler<TEntity, TIdentifierType>overUpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType>; the request-validator bridgeCommandRequestValidator<TCommand, TRequest>overICommandWithRequest<out TRequest>; the upcaster contractIEventUpcaster; the export contributor contractIUserDataExportSection; the process-manager schedulerIProcessTimeoutScheduler; the webhook fan-outWebhookFanOutHandler<TEvent>; the builderMmcaApplicationPipelineBuilder; and the private markersDecoratorPipelineSealandQueryCachingOptIn. Externals: FluentValidation (AddValidatorsFromAssemblyContaining,AddValidatorsFromAssembly,IValidator<>),Microsoft.Extensions.DependencyInjection.Extensions(TryAdd*,TryAddEnumerable),Microsoft.Extensions.Options(IValidateOptions<>,ValidateOnStart),System.Reflection.Concept introduced, the CQRS decorator pipeline wiring order.
[Rubric §6, CQRS and Event-Driven]assesses whether cross-cutting handler concerns are applied uniformly;[Rubric §2, Design Patterns]covers the Decorator pattern itself (the individual decorators are taught in group-05). Decoration uses the framework's ownTryDecorateWithhelper, not a third-party container extension, and each decoration wraps the registration as it stands, so the last one applied is the outermost at runtime.AddApplicationDecorators(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:145) hides that inversion: it writes each pipeline as a list in execution order, outermost first, and the privateDecorateInExecutionOrder(:403-409) walks the list backwards, applying the innermost decorator first. The command list is ViewAs, FeatureGate, Authorization, Logging, Caching (opt-in), Validating, Timeout, Transactional (:168-178), which is the nesting its own XML doc draws (:90-101):ViewAsCommandDecorator (outermost, short-circuits with Forbidden for a view-as caller) -> FeatureGateCommandDecorator (short-circuits if the feature flag is off) -> AuthorizationCommandDecorator (short-circuits with Forbidden if IRequiresPermission) -> LoggingCommandDecorator (captures the duration of everything inside it) -> CachingCommandDecorator (invalidates cache only AFTER the transaction commits) -> ValidatingCommandDecorator (short-circuits with Result.Failure on validation errors) -> TimeoutCommandDecorator (applies the command's own budget if IHasTimeout) -> TransactionalCommandDecorator (DB transaction if ITransactional) -> ConcreteHandler (the actual business logic)The Caching layer is present only when the host called
AddQueryCaching()(seeQueryCachingOptIn):AddApplicationDecoratorsreads the opt-in once (:165) and otherwise spreadsType.EmptyTypesinto that slot, leaving every other position unchanged (:162-164,:174,:186). Queries get a chain of up to six with no view-as guard, FeatureGate, Authorization, Logging, Caching (opt-in), Validating, Timeout, handler (:181-189, drawn at:104-113). The ordering is not arbitrary, and the doc's design rationale gives a reason per position (:116-142): the view-as guard is outermost on commands so a caller holding a read-only view-as token is refused every command before any other work (ADR-137); feature gating is outermost on queries and directly inside the view-as guard on commands, so a disabled feature costs nothing and answers identically for every caller rather than leaking which permission guards it; authorization sits directly inside it and outside caching, so a denied request neither reads nor populates the cache; logging measures only enabled executions; validation sits outside the transaction on the command side so a malformed command never opens one, but inside caching on the query side, because a cached entry can only exist because that query already passed validation once; cache invalidation sits outside validation so cache is cleared only after a valid committed mutation; and the timeout budget sits inside validation and outside the transaction so it covers the database work that actually hangs and cancels the transaction rather than leaving it open, while on the query side it is innermost so a cache hit never starts a budget.[Rubric §11, Security]is why the two authorization decorators are registered unconditionally with aTryAddSingleton<IPermissionRegistry, UnconfiguredPermissionRegistry>()fallback (:154, comment at:149-153), paired with the identicalTryAddSingleton<IPermissionCatalog, UnconfiguredPermissionRegistry>()fallback added immediately after it (:160, comment at:156-159) so an administration surface mounted on a host with no permission model renders an empty catalog list rather than failing to activate: the pipeline cannot activate without a registry at all, so a host with no permission model still resolves every handler while a host that declared its grants (AddAuthorizationPolicies/AddPermissions) keeps its own registry and its own catalog. The order itself is the decision recorded in ADR-014.Concept introduced, the ordering rule as an enforced invariant. This file is the one place where register-order versus execute-order inversion has to be held in mind, and it is also where the framework stops relying on a reader holding it.
AddApplicationDecorators()ends by sealing the collection withDecoratorPipelineSeal(:191), every handler-contributing entry point on the collection opens withThrowIfPipelineSealed(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:147insideAddApplicationDecorators,DependencyInjection.ModuleScanning.cs:50,DependencyInjection.Crud.cs:80,:142,:193,MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:225insideAddQueryCaching, whose flag would otherwise be read too late, and:286insideAddMmcaApplicationPipeline), andAddMmcaApplicationPipeline(configure)(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:284-293) packages the whole sequence so the decorators are last by construction. The webhook delivery handler takes the other route to the same guarantee:AddWebhookDelivery()is an extension onMmcaApplicationPipelineBuilderrather than on the collection (DependencyInjection.Webhooks.cs:86,:94), so it can only run inside the pipeline callback, ahead of the decorators, and itsDeliverWebhookInternalCommandHandlerregistration (:97) is wrapped like any other.[Rubric §15, Best Practices & Code Quality]and[Rubric §14, Testability]:VerifyDecoratorPipeline()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:321) is the fitness hook that proves the result, and it works on descriptor shape alone, never building a provider, so a test does not have to register a double for every decorator dependency (:306-310).Concept introduced,
ScanModuleApplicationServices, the convention scanner.[Rubric §5, Vertical Slice](one call wires a whole module's slice types) and[Rubric §14, Testability](handler registration is reproducible in a test host with the same one call). Both overloads live inDependencyInjection.ModuleScanning.cs. The marker overload (:29-31, constrainedwhere TAssemblyMarker : classat:30) just resolvestypeof(TAssemblyMarker).Assemblyand forwards to theAssemblyoverload (:47, null-guarded at:49), which runs nineAddAssignableTypespasses (the framework's own scanner inServiceCollectionDecoration,MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:59) over that single assembly, each with a deliberate lifetime andScanRegistrationshape: domain event handlers (IDomainEventHandler<>, singleton,ImplementedInterfaces, because they create their own scopes,:52-53), integration event handlers (IIntegrationEventHandler<>, singleton,:55-56), DTO mappers (IEntityDTOMapper<,,>, scoped,SelfWithInterfaces,:58), the opt-in DTO projectors (IEntityDTOProjector<,,>, scoped,:60-63, so an entity that has one gets server-side projection on its list reads and one that has none keeps materialize-then-map), request mappers (IEntityRequestMapper<,,>, scoped,:65), update appliers (IEntityUpdateApplier<,,>, scoped,:67-71), command-aware appliers (IEntityUpdateCommandApplier<,,,>, scoped,:73-76), command handlers (ICommandHandler<,>, scoped,:78) and query handlers (IQueryHandler<,>, scoped,:80), followed byAddValidatorsFromAssembly(:82). After the passes, a reflection loop (:86-100) finds every type in the assembly implementingICommandWithRequest<TRequest>, constructsCommandRequestValidator<TCommand, TRequest>andIValidator<TCommand>withMakeGenericType, andTryAddTransients the pair (:99), so a command that embeds its own request DTO gets a bridging validator for free.TryAddis load-bearing here: an explicitIValidator<TCommand>picked up by the earlierAddValidatorsFromAssemblypass always wins.Concept introduced, generic write-side registration.
[Rubric §15, Best Practices & Code Quality]: all four members live inDependencyInjection.Crud.cs.AddEntityCrud<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest>()(:74) replaces the three hand-written handler classes a straightforward CRUD aggregate would otherwise need, registeringCreateEntityHandler,UpdateEntityHandlerandDeleteEntityHandlerclosed over the aggregate's own types plus the update command's validator bridge (:82-96). Two details in its doc are the teaching points. First, the registrations are closed generics, not open, because decoration wraps closed service types: an openICommandHandler<,>registration would resolve completely undecorated andVerifyDecoratorPipeline()could not see it. Second, everything isTryAdd, so an aggregate that outgrows one verb registers its own handler for that verb before this call and keeps the generic pair for the other two.AddEntityUpdateVerb<..., TApplier>()(:136) registers one verb of the update path discriminated by its applier type, andAddEntityUpdate<TCommand, ...>()(:187) does the same for a derived command that carries state beside the request. All three route their validator wiring throughAddCommandRequestValidator<TCommand, TRequest>()(:220, the singleTryAddTransientat:223), the explicit form of what the scan's reflection bridge does for commands it can see. ADR-099 is the decision record.Concept introduced, the accumulating contributor registration.
[Rubric §30, Compliance, Privacy and Data Governance]assesses whether data-subject obligations are met by design: both members live inDependencyInjection.Extensibility.cs.AddUserDataExportSection<TSection>()(:38) is how each module contributes the slice of a person's data it owns to one export document (ADR-076). The mechanism is two lines,TryAddScoped<TSection>()thenTryAddEnumerable(ServiceDescriptor.Scoped<IUserDataExportSection, TSection>())(:41-42), and both halves matter.TryAddEnumerablede-duplicates by implementation type, so registering the same section twice adds it once while two different sections both survive, which a plainAddScopedwould not guarantee. Scoped, not singleton, so a section runs inside the request's unit of work and may take repositories or gRPC clients (:27-29). Registration order is the order the sections appear in the export document (:20-26).AddEventUpcaster<TSource, TTarget, TUpcaster>()(:81-88) uses the identical idiom one lifetime up:TryAddEnumerable(ServiceDescriptor.Singleton<IEventUpcaster, TUpcaster>())(:86), singleton because upcasters are pure functions over an event instance, withTSourceandTTargetnamed explicitly so the compiler checks the shape at the registration site (ADR-090, rationale at:55-67).AddWebhookEvent<TEvent>(eventType)(DependencyInjection.Webhooks.cs:41) applies the sameTryAddEnumerableidiom to the singletonWebhookFanOutHandler<TEvent>(:80), after validating the type name (:44-50) and refusing a name already used for another type or a type already published under another name (:52-77); registering the same pair twice returns early (:59-62). ADR-142 is the decision record for webhooks.Walkthrough
AddApplication()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:39): fourTryAddSingletoncalls,IDomainEventDispatcher(:41),IEventUpcasterRegistry(:47, registered unconditionally because with no upcasters it is an empty registry whose operations are the identity, so both delivery paths can depend on it without a null check,:43-46),INavigationMetadataProvider(:49) andIEntityQueryPipeline(:50); an open-generic scopedINavigationPopulator<>defaulting to the no-opNullNavigationPopulator<>(:58), so a module registers a closed populator only for an entity with a cross-data-source navigation and the container prefers that closed registration (:52-57); a scopedISoftDeletedUserMarkerWriterregistered through a factory (:63-65), because a Development host validates every registration at build and only a factory defers the writer's dependencies, so a host that issues no tokens still starts (:60-62);AddValidatorsFromAssemblyContaining<ClassReference>()(:70) to register the framework's own validators, which a module-level scan would never reach because it only scans the module's own assembly (:67-69); and the handler for the erasure's durable push-installation cleanup,DeleteUserPushInstallationsInternalCommand(:75), registered here, ahead of the decorators, so a host that schedules it needs no registration of its own and the processor finds a decorated handler for the row (:72-74).AddApplicationDecorators()(:145): guard, permission-registry fallback plus the parallel permission-catalog fallback, the query-caching opt-in read (:165), twoDecorateInExecutionOrdercalls (seven or eight command decorators, five or six query decorators, depending on the opt-in), seal.AddQueryCaching()(:223): guarded (:225), registers theQueryCachingOptIninstance (:227). Off by default; must run before the decorators, either beforeAddMmcaApplicationPipeline(...)or inside its callback (:216-220).ScanModuleApplicationServices<TAssemblyMarker>()(DependencyInjection.ModuleScanning.cs:29, constrainedwhere TAssemblyMarker : classat:30) andScanModuleApplicationServices(Assembly)(:47, null-guarded at:49): the nine-pass scanner plus the request-validator loop.AddEntityCrud/AddEntityUpdateVerb/AddEntityUpdate/AddCommandRequestValidator(DependencyInjection.Crud.cs:74,:136,:187,:220): the generic write side.AddUserDataExportSection<TSection>()(DependencyInjection.Extensibility.cs:38, constrainedwhere TSection : class, IUserDataExportSectionat:39) andAddEventUpcaster<TSource, TTarget, TUpcaster>()(:81): the two accumulating registrations. The export handler itself needs no registration here: apps subclassExportUserDataHandlerBase<TUser, TQuery>in their own Application assembly and the scanner picks the subclass up as anIQueryHandlerlike any other (:32-36).AddProcessManagers()(DependencyInjection.ProcessManagers.cs:24):TryAddScoped<IProcessTimeoutScheduler, ProcessTimeoutScheduler>()plusTryAddSingleton(TimeProvider.System)for a host that registered no clock (:26-27). It registers no handler, so it carries no seal guard and may be called inside or outside the pipeline;AddApplication()registers none of it (:18-22).AddWebhookEvent<TEvent>(eventType)(DependencyInjection.Webhooks.cs:41): one catalog entry, the singleton fan-out handler and theWebhookEventCatalog(:79-81).AddWebhookDelivery()(:94, on the builder): the scoped delivery handler (:97),WebhookSettingsoptions withValidateOnStart(:98) and anIValidateOptions<WebhookSettings>startup check that fails, namingAddWebhooks(configuration), when the host registered no subscription store (:99, doc at:88-92).AddApplicationProfiling()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:237): optional, appliesProfilingCommandDecorator<,>andProfilingQueryDecorator<,>on top withTryDecorateWith(:239-240), for use withApplicationSettings.UseMiniProfiler. It deliberately carries no seal guard, so it can be applied after the pipeline is closed.AddMmcaApplicationPipeline(configure)(:284): guard,AddApplication(), invoke the callback with a newMmcaApplicationPipelineBuilder, returnAddApplicationDecorators()(:286-292). Theconfigurecallback may be null for a host with no modules (:250-257).VerifyDecoratorPipeline()(:321): checks the seal first (:323-328), then walks the collection keeping the last non-keyed generic descriptor perICommandHandler<,>/IQueryHandler<,>service type (:330-343, last-registration-wins is the container's own rule), and reports every surviving entry whoseImplementationFactoryis null (:345-359). The doc explains why that test is sound: decoration rewrites a decorated registration into a factory over a private keyed copy of the original, so an implementation type (or instance) still sitting on the effective registration is proof nothing wrapped it; an open-generic handler registration can never be wrapped, because the container has no open-generic factories, so it is reported too (:311-319).
Why it's built this way:
[Rubric §3, Clean Architecture]: registration lives in a static,partialDependencyInjectionclass at the composition root, so domain and Application types never reference the container. The pervasiveTryAdd*andTryDecorateWithpattern lets a consuming app override any framework default simply by registering its own implementation first. Each file carries its ownextension(...)block, the C# extension-member syntax the framework uses for its public DI surface (ADR-106, and primer §4 for the syntax itself); the webhook file uses the same syntax to extend the builder rather than the collection.Where it's used: by every consuming host. ADC and Store services compose through
AddMmcaServiceHost(for exampleMMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88,MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:32), which callsAddMmcaApplicationPipelinewith the host's pipeline callback (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:158) and addsAddApplicationProfiling()only whenApplicationSettings.UseMiniProfileris true (:164). MMCA.Helpdesk callsAddMmcaApplicationPipelinedirectly, with module discovery in aRegisterstep (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:138,:142).ScanModuleApplicationServices<ClassReference>()is called from each module's own composition root (seeClassReferencefor the call sites).AddUserDataExportSection<TSection>()is called by ADC's Identity module for its three cross-module sections (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:66-68) and by Store'sIdentityModulefor its two (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/IdentityModule.cs:40,:45).VerifyDecoratorPipeline()is called by the architecture and composition tests (MMCA.Store/Tests/Architecture/MMCA.Store.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:68,MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/ApplicationPipelineCompositionTests.cs:160,MMCA.Common/Tests/Hosting/MMCA.Common.ServiceHost.Tests/ServiceHostBuilderExtensionsTests.cs:210).Caveats / not-in-source: several other classes named
DependencyInjectionexist across the framework and the apps (Infrastructure, API, Grpc, UI, Notifications, and one per module) with the same name but different namespaces and methods. This section covers only the MMCA.Common.Application root, whose partial declarations open atMMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:31andDependencyInjection.Crud.cs:14; the others are documented in their own groups.
IModuleSeeder
MMCA.Common.Application ·
MMCA.Common.Application.Modules·MMCA.Common/Source/Core/MMCA.Common.Application/Modules/IModuleSeeder.cs:8· Level 0 · interface
What it is: the Application-layer contract for seeding a module's initial data at startup.
ModuleNamedeclares ownership andSeedAsyncreceives anIServiceProviderso the seeder can resolve whatever it needs. Implementations are auto-discovered byModuleLoaderand run, in module-dependency order, after every module has registered.Depends on: BCL only (
Task,IServiceProvider,CancellationToken).Concept introduced, seeding at the right layer.
[Rubric §3, Clean Architecture]assesses whether each concern lives in the layer that owns it. An Application seeder populates data through service interfaces and never touches aDbContext; a seeder that genuinely needs direct EF access derives the Infrastructure-layer abstractDbSeeder(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Seeding/DbSeeder.cs:11) instead. TheIServiceProviderparameter is deliberate: the loader holds the seeder for the lifetime of composition, so passing the provider (rather than a concrete scoped dependency) is what lets the caller control scoping.[Rubric §7, Microservices Readiness]: seeding is a separate contract fromIModule, so a module that needs no reference data implements nothing extra, and an extracted service seeds only its own module.Walkthrough:
string ModuleName { get; }(MMCA.Common/Source/Core/MMCA.Common.Application/Modules/IModuleSeeder.cs:13) must match the correspondingIModule.Nameso the loader can correlate a seeder to its module and keep it in topological position;Task SeedAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)(:18) is the single work method, and the XML doc states it is called only for enabled modules (:16).Where it's used: discovered by
ModuleLoaderinto a case-insensitive dictionary keyed byModuleName(ModuleLoader.cs:99-104) and kept only when the matching module is enabled (ModuleLoader.cs:127-130). The actual invocation happens at host startup:DatabaseInitializationExtensionscallsmoduleLoader.SeedAllAsync(scope.ServiceProvider, cancellationToken)after schema initialization and tenant-database initialization (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:139). Seeding deliberately runs on the default scope only, not once per tenant, and the comment above the call gives the reason: no module declares which seeders apply per tenant, and running one twice against a shared database is worse than not running it per tenant at all (:107-110). The implementations are one per data-owning module:ConferenceModuleSeeder(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/ConferenceModuleSeeder.cs:13) andIdentityModuleSeeder(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:15) in ADC;CatalogModuleSeeder(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/CatalogModuleSeeder.cs:11),SalesModuleSeeder(.../Sales/MMCA.Store.Sales.API/SalesModuleSeeder.cs:14) andIdentityModuleSeeder(.../Identity/MMCA.Store.Identity.API/IdentityModuleSeeder.cs:12) in Store.
InternalCommandDeadLetter
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IInternalCommandAdministration.cs:102· Level 0 · record (sealed)
What it is: the read-model row
IInternalCommandAdministration.ListDeadLettersAsynchands back for one internal-command row whose retry attempts are exhausted and that will never run again without an explicit requeue.Depends on: BCL types only (
Guid,string,DateTime, the nullablestring?andDateTime?). Nothing first-party, which is why it sits at Level 0 despite being the return shape of a Level 3 interface.Concept introduced, a narrow read projection over an operational queue.
[Rubric §13, Observability and Operability]assesses whether an operator gets exactly what a triage screen needs:DataSourcenames which relational source the row lives in,CommandTypeandScheduledOn/CreatedOnsay what was supposed to run and when,AttemptsandLastErrorsay why it stopped, andDeadLetteredOnsays when it stopped mattering.[Rubric §3, Clean Architecture]: declaring the record in Application, the same layer asIInternalCommandAdministration, keeps the administration contract free of an Infrastructure/EF dependency.Walkthrough: eight positional parameters on a
sealed record(IInternalCommandAdministration.cs:102-110):Id(Guid),DataSource(string),CommandType(string),ScheduledOn(DateTime),CreatedOn(DateTime),Attempts(int),LastError(string?, null only when a row was dead-lettered without ever throwing, for example afterMaxAttemptswas lowered),DeadLetteredOn(DateTime?).Why it's built this way: a positional record gives structural equality for free, which the type's only production consumer,
ListDeadLettersAsync's materialization, does not need but a test comparing expected rows does.Where it's used: the element type of
Task<Result<IReadOnlyList<InternalCommandDeadLetter>>>returned byIInternalCommandAdministration.ListDeadLettersAsync(IInternalCommandAdministration.cs:45), implemented byInternalCommandAdministration(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandAdministration.cs).Caveats / not-in-source: no shipped UI or API endpoint renders this type in this workspace; it is consumed only by the administration implementation and its tests.
InternalCommandDeadLetterNotice
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/InternalCommandDeadLetterNotice.cs:14· Level 0 · record (sealed)
What it is: the small message an
IInternalCommandDeadLetterHandler<in TCommand>receives alongside the abandoned command: which row was dead-lettered, why, with what error, and after how many attempts (InternalCommandDeadLetterNotice.cs:3-5).Depends on: BCL only (
Guid,string,int), which is why it sits at Level 0.Concept introduced, a callback payload that mirrors the operator signal.
[Rubric §13, Observability and Operability]assesses whether the code that reacts to a failure sees the same facts the operator sees.Reasoncarries the machine-readable value the dead-letter counter is tagged with (:8-11), and the processor passes the veryreasonstring it adds toInternalCommandMetrics.DeadLetterCounter(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:651-658), so a callback's log line and the metric agree.[Rubric §3, Clean Architecture]: declaring it in Application, beside the handler contract, keeps a feature's callback free of any reference to the Infrastructure row typeInternalCommandMessage.Walkthrough: four positional parameters on a
sealed record(InternalCommandDeadLetterNotice.cs:14-18):CommandId(Guid, the dead-lettered row's id,:7);Reason(string,attempts_exhaustedorhandler_missingper the doc,:8-11);Error(string, the failure recorded on the row, truncated to the column width,:12);Attempts(int, the attempts made including the final one,:13). The processor builds it asnew InternalCommandDeadLetterNotice(row.Id, reason, truncated ?? message, attempts), whereattemptsis the row's count plus the failing attempt (InternalCommandProcessor.cs:636,:658).Why it's built this way: the two reasons the doc names are exactly the dead-letter paths that still hold a typed command: the processor hands its command over on the
handler_missingandattempts_exhaustedpaths (InternalCommandProcessor.cs:443,:502), while a row dead-lettered aspayload_invalidortype_unresolvable(:408,:421) has no command to deserialize, so no callback and no notice is produced for it (:656,TryDeserializeat:664-674).Where it's used: constructed only in
InternalCommandProcessor.DeadLetterAsync(InternalCommandProcessor.cs:626,:658) and passed throughInternalCommandDispatcher.NotifyDeadLetterAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandDispatcher.cs:76-80) to each registered handler. The one shipped consumer isDeliverPushNotificationPageDeadLetterHandler, which logsnotice.Reasonandnotice.Attemptswhen it marks a notification failed (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageDeadLetterHandler.cs:53). Covered byInternalCommandDeadLetterCallbackTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/Processing/InternalCommandDeadLetterCallbackTests.cs).Caveats / not-in-source:
Reasonis a plainstring, not an enum, so the two documented values are a convention a callback compares against by literal; nothing in the type rejects another value.
InternalCommandNameAttribute
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/InternalCommandNameAttribute.cs:25· Level 0 · class (sealed)
What it is: an attribute that gives an
IInternalCommandimplementation a stable, explicit serialization identity, stored in place of its CLR type name so the command can be renamed or moved without breaking rows already persisted.Depends on:
System.Attributeonly.Concept introduced, a stable wire identity decoupled from the CLR type name.
[Rubric §29, Reliability and Resilience]: a durable job queue persists a command's type identity alongside its serialized payload, and a CLR type name is not a safe long-term identity, a rename or a namespace move changes it and orphans every already-scheduled row.InternalCommandNameAttributebreaks that coupling: the constructor validates and stores an explicitName(:58,Validatedhelper at:66-70) that a resolver looks up independently of the type's runtime name.Walkthrough:
public sealed class InternalCommandNameAttribute(string name) : Attribute(:25), a primary-constructor attribute with one member,public string Name { get; } = Validated(name);(:58).Validated(:66-70) callsArgumentException.ThrowIfNullOrWhiteSpace(name)before returning it, so a blank identity fails at attribute-application time (effectively at the first resolution, since attribute arguments are evaluated lazily) rather than silently landing in storage where it could never be resolved back to a type.Why it's built this way: rejecting an empty name at construction, rather than allowing it and failing later at lookup, moves the failure to the earliest possible point and keeps
InternalCommandNameResolverfree of a null/blank branch.Where it's used: read by
InternalCommandNameResolver(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandNameResolver.cs) to translate between a command's declared name and its CLR type, and byInternalCommandMessage(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandMessage.cs) when persisting a scheduled row.IInternalCommandimplementations are expected to carry it, though the interface itself does not enforce that at compile time.Caveats / not-in-source: nothing in the
IInternalCommandinterface contract requires this attribute; a command with noInternalCommandNameAttributefalls back to whateverInternalCommandNameResolverdoes for an unnamed type, not documented at this type's own declaration site.
Scope
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/InternalCommandExecution.cs:50· Level 0 · class (private, sealed, nested)
What it is: the disposable handle
InternalCommandExecution.Begin()returns. Disposing it puts the ambient "running a scheduled internal command" flag back to the value it held before the scope opened.Depends on:
System.IDisposableand the enclosing class's privateAsyncLocal<bool> Activefield (InternalCommandExecution.cs:24). Nothing else, which is why it sits at Level 0.Concept: the restore-on-dispose scope, taught under
InternalCommandExecution. This type is only the "restore" half.Walkthrough: a primary-constructor class,
private sealed class Scope(bool previous) : IDisposable(InternalCommandExecution.cs:50), whose single memberDispose()assigns the capturedpreviousback toActive.Value(:51). It holds no other state, so exactly two instances are ever needed, and the enclosing class creates both once as static fields:OutermostScope = new Scope(previous: false)(:45) andNestedScope = new Scope(previous: true)(:47).Why it's built this way: because the only thing a handle has to remember is one boolean, the two possible handles are preallocated and shared, so opening a scope around every internal-command dispatch allocates nothing. Disposing a shared instance is safe because
Dispose()writes a constant rather than releasing a resource, and a secondDispose()writes the same value again.Where it's used: only as the return value of
InternalCommandExecution.Begin()(InternalCommandExecution.cs:43). It isprivate, so no caller can name or construct it.Caveats / not-in-source: the many usage sites the inventory attributes to
Scopeare name collisions with unrelated members calledScope(check-in scopes, metadata scopes); the only real consumer of this nested class is the enclosingBegin().
IModule
MMCA.Common.Application ·
MMCA.Common.Application.Modules·MMCA.Common/Source/Core/MMCA.Common.Application/Modules/IModule.cs:7· Level 1 · interface
What it is: the contract every pluggable module implements: a
Name, an optionalDependencieslist, aRequiresDependenciesflag, aRegistermethod that wires the module's services, and an optionalRegisterDisabledStubsmethod for the cross-module stubs used when the module is switched off.Depends on:
ApplicationSettings(Level 0, passed intoRegister); externallyMicrosoft.Extensions.DependencyInjection(IServiceCollection) andMicrosoft.Extensions.Configuration(IConfigurationBuilder).Concept introduced, the module system as a single composition contract.
[Rubric §5, Vertical Slice]assesses whether features cluster into cohesive, self-contained boundaries: a module (Conference, Engagement, Identity, Notification, Catalog, Sales, Tickets) is the top-level cohesion unit, and it registers all of its own services (handlers, EF configurations, repositories, validators) through oneRegistercall.[Rubric §7, Microservices Readiness]assesses independent deployability: modules declare dependencies by name (string), soModuleLoadercan compute a safe startup order with no compile-time reference between modules. When a dependency is disabled andRequiresDependenciesis left at itsfalsedefault, the depended-on module registers stubs throughRegisterDisabledStubsso cross-module interfaces stay resolvable. An extracted ADC service host needs no stub at all: the Conference service names only its own module and satisfies Engagement'sIBookmarkCountServicewith a gRPC adapter registered byAddEngagementBookmarkCountClient(MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:323-327).Walkthrough: five members, three of them with default interface implementations, so a minimal module supplies only
NameandRegister.string Name { get; }(IModule.cs:12, required);IReadOnlyList<string> Dependencies => [](:17, default empty);bool RequiresDependencies => false(:23, default tolerant);void Register(IServiceCollection, IConfigurationBuilder, ApplicationSettings)(:28, required);void RegisterDisabledStubs(IServiceCollection services) { }(:34, default no-op). Note thatRegistertakes anIConfigurationBuilder, not a builtIConfiguration, so a module can add its own configuration sources before its services bind them, which is exactly what the loader exploits to inject per-module JSON files.Why it's built this way: ADR-059 is the decision record for this contract, and ADR-008 is the topology it enables ("each service is the monolith with one module enabled"). Making
IModulethe single composition boundary means extraction is a deployment concern rather than a rewrite, and default interface members keep the common case ceremony-free while leaving the extraction hooks available.Where it's used: implemented by every module's API project, for example
ConferenceModule(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/ConferenceModule.cs:13),EngagementModule(.../Engagement/MMCA.ADC.Engagement.API/EngagementModule.cs:14),IdentityModule(.../Identity/MMCA.ADC.Identity.API/IdentityModule.cs:13),NotificationModule(.../Notification/MMCA.ADC.Notification.API/NotificationModule.cs:15), Store'sCatalogModule/SalesModule/IdentityModule, and Helpdesk's singleTicketsModule(MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.API/TicketsModule.cs:13). Discovered, sorted, and invoked byModuleLoader; the name is additionally pinned as a fitness rule byModuleConformanceTestsBase, because renaming it silently disables the module's configuration and drops it from other modules' dependency graphs (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Layering/ModuleConformanceTestsBase.cs:42).
InternalCommandExecution
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/InternalCommandExecution.cs:22· Level 1 · class (static)
What it is: an ambient marker that answers one question for code deep inside a handler: "is this flow executing a scheduled internal command right now?" The internal-command processor turns it on around each dispatch, and a handler that one command type serves on two paths reads it to tell the durable path from an inline one (
InternalCommandExecution.cs:3-6).Depends on: its nested handle
ScopeandSystem.Threading.AsyncLocal<bool>(BCL). The marker exists forIInternalCommandwork scheduled throughIInternalCommandScheduler, but it references neither.Concept introduced, an ambient execution-path flag over
AsyncLocal<T>.AsyncLocal<T>stores a value in theExecutionContext, so it flows into everyawaitcontinuation and child task started from the flow that set it, and a change made inside an async method does not leak back out to the caller's context. The class doc names this as the same mechanismQueryTagScopeuses (:8-9).[Rubric §29, Reliability and Resilience]assesses whether failures are surfaced to the mechanism that can recover from them: the case this exists for is an anonymous HTTP endpoint that must answer success whatever happens (anti-enumeration), while the same command, run from the durable queue, must report a transient failure so the row is retried instead of acknowledged (:14-18).[Rubric §2, Design Patterns]: the alternative would be a second command type or a payload flag; an ambient context keeps one command and one handler and lets only the execution path differ. The doc also states the inheritance rule on purpose: a command dispatched inline from inside a running internal command inherits the marker, which is correct, because its failure fails the row that is running (:10-11).Walkthrough
Active(:23): the privatestatic readonly AsyncLocal<bool>,falseby default.IsActive(:30): readsActive.Value. It isfalsefor a request, a background service, or a test that dispatches a handler directly (:25-29).Begin()(:38-43): captures the current value, setsActive.Value = true, and returns the preallocatedScopethat restores what it captured:NestedScopewhen the flag was already on,OutermostScopeotherwise (:42, fields at:45,:47). Restoring the previous value rather than writingfalseis what lets nested scopes unwind correctly (:33-35).
Why it's built this way: the doc says the processor opens the scope and "nothing else should" (
:9-10), so the flag means exactly one thing. Two shared handle instances make the per-dispatch cost a field read and two writes. ADR-114 is the decision record for the durable queue the marker belongs to.Where it's used: opened by
InternalCommandProcessorwithusing var execution = InternalCommandExecution.Begin();immediately before it dispatches a row (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:543). Read bySendEmailConfirmationHandlerBase<TUser, TCommand>to choose its path: with the flag set it runs the send, otherwise it only schedules the command and answers success (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/SendEmailConfirmationHandlerBase.cs:85-87). On that durable path a throttle refusal returns its failure (:132-139) and a send failure propagates with no catch, so the row is retried (:141-146). Covered byInternalCommandProcessorTestsandEmailConfirmationHandlerBaseTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/Processing/InternalCommandProcessorTests.cs,MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/EmailConfirmationHandlerBaseTests.cs).Caveats / not-in-source: nothing enforces "only the processor calls
Begin()": the method ispublic, and the restriction is a documented convention (:9-10).
ModuleLoader
MMCA.Common.Application ·
MMCA.Common.Application.Modules·MMCA.Common/Source/Core/MMCA.Common.Application/Modules/ModuleLoader.cs:16· Level 2 · class (sealed, partial)
What it is: the engine of the module system. It reflects over the assemblies the host names to find every
IModuleandIModuleSeederimplementation, sorts the modules into dependency order with Kahn's topological sort, registers each enabled module into the DI container, and gives each disabled module its stub registrations instead, so a dependent always resolves something.Depends on:
IModule(Level 1),IModuleSeeder(Level 0),ApplicationSettings(Level 0),ModulesSettings(Level 1). Externals:IServiceCollection/IConfigurationBuilder,Microsoft.Extensions.Logging(source-generated[LoggerMessage]methods,NullLogger<T>),System.Diagnostics.Stopwatch,System.Reflection.Concept introduced, Kahn's topological sort for DI registration ordering.
[Rubric §2, Design Patterns]assesses use of the right algorithm for the problem: ordering items so each appears after everything it depends on is textbook topological sort, andTopologicalSort(ModuleLoader.cs:249) implements the BFS-based Kahn variant.[Rubric §7, Microservices Readiness]: the loader is what makes partial enablement (one module per service host) work at all.[Rubric §15, Best Practices & Code Quality]: modules name their dependencies as strings and the loader resolves and sorts them at startup, so adding a module is purely additive, with no central registration list to edit.[Rubric §13, Observability and Operability]: eight[LoggerMessage]partial methods (:301-323) give allocation-free structured diagnostics of which modules loaded, in what order, with which satisfied or unsatisfied dependencies, how long eachRegistertook, which seeder names no discovered module (atWarning,:316-317), and which assemblies failed to scan or loaded only partially (those two atError,:319-323).Walkthrough
- State (
ModuleLoader.cs:18-20): three private lists,_enabledModules,_seeders,_disabledModuleNames, the first and third surfaced as the read-onlyEnabledModules(:23) andDisabledModuleNames(:26) properties. The loader holds no other state: it keeps no record of what a disabled module's stubs registered and no copy of the settings it was given.Logger(:32) is aninit-onlyILogger<ModuleLoader>defaulting toNullLogger<ModuleLoader>.Instance, so the loader runs silently unless a host supplies one. DiscoverAndRegister(:57-62) is the single entry point, and it takes the assemblies to scan as a required parameter. There is no ambient-scan overload, and the XML doc gives the reason: an AppDomain scan only sees assemblies already loaded, so a module assembly that is referenced but not yet touched by any code path would be silently absent from discovery (:47-50). ItsconfigurationBuilderparameter is the host's configuration, handed unchanged to each enabled module'sRegister: the loader adds no configuration source of its own, so a module reads the host's configuration (:40-43). The documented exceptions are a required dependency that is disabled and two modules (or two seeders) sharing a name, compared case-insensitively (:52-56).- Discovery (
:69-104): flattensmoduleAssembliesthroughGetTypes()inside atrywith two catches, and neither aborts the whole scan. AReflectionTypeLoadException(the shape a missing transitive reference produces) is caught first (:76-83): it joins the non-nullLoaderExceptionsmessages, logsLogAssemblyPartiallyLoadedatError, and keeps every type that did load (ex.Types.OfType<Type>(),:82), so one unloadable type does not make the assembly's other modules vanish. Any other exception (:85-90) logsLogAssemblyScanFailed, also atErrorand with the exception attached, and skips that assembly; that deliberately broad catch carries a scopedCA1031suppression whose comment states the rule, one unloadable assembly must not stop module discovery (:84,:86). The code comment gives the reason forErrorrather thanWarning: a module that silently fails to register is an outage that looks like a configuration choice (:64-68). It then instantiates every concrete, non-abstract, non-interfaceIModuleviaActivator.CreateInstance(:94-97) and indexes everyIModuleSeederbyModuleNamethroughIndexByName(:99-104). - Name indexing (
:106-109): the modules are indexed byNamethe same way (:108), because names match case-insensitively everywhere (settings, dependencies, seeders), so two modules whose names differ only by case are the same module to the loader (:106-107).IndexByName(:139-158) builds anOrdinalIgnoreCasedictionary and, on a second item with a name already present, throwsInvalidOperationExceptionnaming both types and their assemblies (:146-151); its doc gives the reason: otherwise the loader would register one silently or fail with a bare duplicate-key error that names neither type (:134-138).WarnOnUnmatchedSeeders(:109,:165-174) then logsLogSeederUnmatchedatWarningonce per seeder whoseModuleNamenames no discovered module, since such a seeder can never run and after a module rename would silently drop that module's seeding; a seeder of a discovered but disabled module is skipped by design and not reported (:160-164). - Per-module loop (
:114-131): for a module disabled perModulesSettings.IsModuleEnabled, it logs, callsmodule.RegisterDisabledStubs(services), records the name, and continues (:116-122). An enabled module runsValidateModuleDependenciesthenRegisterEnabledModule(:124-125), and if a seeder with a matching name exists it is appended to_seeders(:127-130). ValidateModuleDependencies(:176): computes the module's disabled dependencies (:182-184), subtracts those declared remote viaModulesSettings.IsDependencyRemote(:186-188), and throwsInvalidOperationExceptiononly if a genuinely unsatisfied dependency remains andRequiresDependenciesis true; the message spells out the three remediations, enable the module, disable this one, or add the name toModules:{Name}:RemoteDependencies(:190-198). Otherwise it logs a warning per unsatisfied-but-tolerated dependency (:200-203) and an information line per remote-satisfied one (:205-208). The code comment places the cross-process replacement (for example a typed gRPC client) on the host, afterDiscoverAndRegisterreturns (:178-181).RegisterEnabledModule(:211): logs the module and its dependency count, times themodule.Registercall with aStopwatchand logs the elapsed milliseconds (:219-222), then appends the module to_enabledModules(:223).SeedAllAsync(:233): awaits each collected seeder'sSeedAsyncin registration (that is, topological) order, withConfigureAwait(false)(:235-238).TopologicalSort(:249): buildsmodulesByName,inDegree, and a reverse-adjacencydependentsmap, allOrdinalIgnoreCase(:251-257); while building the graph it ignores dependencies on modules that were not discovered (:264-265), deferring those to registration-time validation. It seeds aQueue<string>with the zero-in-degree modules (:273-274) and drains it, decrementing each dependent's in-degree and enqueuing at zero (:277-288). If fewer modules were emitted than exist, the remainder form a cycle, and it throwsInvalidOperationExceptionnaming them (:291-296).
- State (
Why it's built this way: convention over configuration. Discovery plus sort means no manual ordering and no module-registration list to keep in sync, which is the decision recorded in ADR-059 (a disabled module is represented by stub registrations rather than by absence, so a dependent always resolves something). Making the assembly list an explicit parameter rather than an ambient scan trades one line at the host for deterministic discovery.
Where it's used: constructed by
ModuleHostExtensions.AddModuleHost, which attaches a logger when the host supplies one and registers the loader as a singleton (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostExtensions.cs:75-79), then hands it back on aModuleHostContextwhoseRegisterModulesstep is the actualDiscoverAndRegistercall (ModuleHostContext.cs:69-100). Every ADC and Store service registers that step inside its application pipeline, for example ADC Conference (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:360, comment at:330) and Store Catalog (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:111, inside theConfigurePipelinecallback at:106). The MMCA.Helpdesk monolith takes the same path: it callsAddModuleHostwith a console logger, namingtypeof(TicketsModule).Assemblyas the one assembly to scan (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:25-30), and registersmoduleHost.RegisterModulesin its pipeline (:136). Seeding runs later, fromDatabaseInitializationExtensions(DatabaseInitializationExtensions.cs:139).Caveats / not-in-source: nothing in the loader checks, after the container is built, that a dependency declared in
RemoteDependencieswas actually re-wired by the host.ValidateModuleDependenciestrusts the declaration (:186-188), so a typo in aRemoteDependenciesentry or a forgotten typed gRPC client surfaces at the first request that resolves the dependency (as a resolution failure or a stub no-op), not at startup.
IInternalCommand
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IInternalCommand.cs:38· Level 3 · interface
What it is: the marker contract for a unit of deferred work in the internal-command durable job queue: a command that can be scheduled to run later, in-process, by
IInternalCommandSchedulerinstead of executing immediately on the caller's own request.Depends on:
ICommand<Result>(group-05), so anIInternalCommandis, by construction, also an ordinary CQRS command that resolves anICommandHandler<TCommand, Result>and runs through the same decorator pipeline as any other command.Concept introduced, deferred execution without leaving the CQRS pipeline.
[Rubric §29, Reliability and Resilience]assesses whether background work survives a process restart: anIInternalCommandscheduled throughIInternalCommandScheduler.ScheduleAsyncis durable, a row in theInternalCommandstable, not an in-memory timer, so a host crash between scheduling and execution loses nothing.[Rubric §6, CQRS and Event-Driven]: because the interface only narrowsICommand<Result>, the framework does not need a second handler abstraction or a second decorator pipeline for deferred work;InternalCommandProcessorresolves and invokesICommandHandler<TCommand, Result>exactly as the synchronous path does, so feature gating, authorization, validation, timeout and transaction all still apply.Walkthrough: a single-line marker,
public interface IInternalCommand : ICommand<Result>;(:38), with no members of its own. The result type is fixed to plainResult(no payload), which the type's own doc explains is deliberate: a deferred command runs with nobody waiting synchronously for a return value, so there is nothing to hand a caller.Why it's built this way: narrowing rather than introducing a parallel handler contract keeps a command implementer's mental model single: "is this command run now or later" is a scheduling decision, not a different kind of command.
Where it's used: the constraint on
IInternalCommandScheduler.ScheduleAsync'scommandparameter (IInternalCommandScheduler) and onInternalCommandDispatcher's resolution ofICommandHandler<TCommand, Result>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandDispatcher.cs). Implemented across both ADC and Store wherever a command is meant to run deferred, for exampleSendEmailConfirmationCommand(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendEmailConfirmation/SendEmailConfirmationCommand.cs).Caveats / not-in-source: the interface itself does not require an
InternalCommandNameAttribute; whether an implementation needs one is a detail ofInternalCommandNameResolver, not of this contract.
IInternalCommandAdministration
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IInternalCommandAdministration.cs:17· Level 3 · interface
What it is: the operator-facing contract over the internal-command queue: count what is pending, list what has dead-lettered, requeue dead letters, and purge completed rows on demand rather than waiting for the retention sweep.
Depends on:
InternalCommandDeadLetter(Level 0, the element type ofListDeadLettersAsync's result); BCL (Guid,TimeSpan,IReadOnlyCollection<Guid>); the framework'sResult<T>return convention.Concept introduced, an administration surface as its own contract, separate from the scheduler.
[Rubric §13, Observability and Operability]assesses whether an operational queue is inspectable and correctable without a direct database console: every method here answers a question an on-call engineer actually asks ("how much is backed up", "what died and why", "put it back", "clean up what finished").[Rubric §1, SOLID](ISP): this is a separate interface fromIInternalCommandSchedulerrather than a wider one, so a host that only ever schedules work never has to satisfy or fake the administration methods, and an administration UI depends on exactly the surface it needs.Walkthrough: four methods, all
Task<Result<T>>and all taking an optionaldataSourcefilter (nullmeans every source this host owns).CountPendingAsync(string? dataSource, CancellationToken)(:28): counts rows not yet processed, not dead-lettered, attempts not exhausted, including rows whose scheduled instant is still in the future, because that is backlog the host has already accepted.ListDeadLettersAsync(string? dataSource, int skip, int take, CancellationToken)(:45-49): a paged, oldest-first list ofInternalCommandDeadLetterrows.skipis bounded to 0 through 10,000 and a larger offset is a validation failure, because each source returns up toskip + takerows for the in-memory merge (:38-41); the implementation enforces it withMaxSkip = 10_000and anInternalCommands.InvalidSkipvalidation error (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandAdministration.cs:50-53, check at:94).RequeueAsync(string? dataSource, IReadOnlyCollection<Guid>? ids, CancellationToken)(:66-69): resets attempts to zero and clears the dead-letter stamp and claim lease so the next poll cycle picks the row back up, deliberately keepingLastError(the doc's own reasoning: the failure reason is the first thing anyone asks after a requeue) and leaving the scheduled instant untouched so a requeued row is immediately due.idsnull or empty requeues every dead letter in the selected scope.PurgeProcessedAsync(string? dataSource, TimeSpan olderThan, CancellationToken)(:83-86): deletes completed rows older than the threshold; pending and dead-lettered rows are never touched by this call, only rows carrying a completion stamp.TimeSpan.Zeropurges every completed row (:77-80).
Why it's built this way: every method takes an explicit
dataSourcefilter rather than assuming one database, consistent with the framework's database-per-module model, so an administration surface mounted on a multi-source host can scope an operation to one source or run it across all of them with the same call.Where it's used: implemented by
InternalCommandAdministration(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandAdministration.cs:40) and registered withTryAddScopedinMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:170. ItsRequeueAsyncis the operationIInternalCommandDeadLetterHandler<in TCommand>documents as not undoing what a dead-letter callback recorded. ADC's integration tests resolve it to inspect the queue (MMCA.ADC/Tests/Integration/MMCA.ADC.CrossService.IntegrationTests/Infrastructure/CrossServiceTestBase.cs:286,MMCA.ADC/Tests/Integration/MMCA.ADC.Identity.IntegrationTests/Auth/EmailConfirmationFlowTests.cs:155).Caveats / not-in-source: no shipped ADC or Store admin page in this workspace calls this interface; outside the Infrastructure implementation its only callers are tests (Common's own and the ADC integration tests above).
IDeleteBlobInternalCommand
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IDeleteBlobInternalCommand.cs:21· Level 4 · interface
What it is: a narrow marker interface for the one recurring shape of deferred blob cleanup: an
IInternalCommandwhose only payload is the name of the blob to delete.Depends on:
IInternalCommand(Level 3), so any implementation is also schedulable throughIInternalCommandSchedulerand runs through the ordinary CQRS decorator pipeline like any other internal command.Concept introduced, a shared contract for a recurring deferred-cleanup shape.
[Rubric §1, SOLID](ISP): rather than each caller inventing its own "delete this blob later" command shape, the interface pins the one property every such command needs,string BlobName { get; }(IDeleteBlobInternalCommand.cs:24), and leaves everything else (which container, which retry policy) to the concrete command and its handler.[Rubric §29, Reliability and Resilience]: naming the shape letsDeleteBlobInternalCommandHandlerBase<TCommand>be written once and reused by every blob-owning feature instead of duplicating the delete-then-tolerate-not-found logic per caller.Walkthrough: a single-member interface,
public interface IDeleteBlobInternalCommand : IInternalCommand(:21), narrowingIInternalCommandwith onestring BlobName { get; }property (:24-25) that names the blob to delete.Why it's built this way: keeping the interface to one property is what lets the generic handler base below be written against
TCommand : IDeleteBlobInternalCommandwith nothing else to assume about the concrete command.Where it's used: implemented by
DeleteSessionAssetBlobInternalCommand(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/DeleteSessionAssetBlob/DeleteSessionAssetBlobInternalCommand.cs) andDeleteAvatarBlobInternalCommand(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteAvatarBlob/DeleteAvatarBlobInternalCommand.cs), each paired with a handler that derives fromDeleteBlobInternalCommandHandlerBase<TCommand>.Caveats / not-in-source: the interface makes no statement about which storage container or account the blob lives in; that is resolved entirely inside whichever
IFileStorageServiceimplementation the handler was constructed with.
IInternalCommandDeadLetterHandler<in TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IInternalCommandDeadLetterHandler.cs:34· Level 4 · interface (generic, contravariant)
What it is: an optional callback the internal-command processor runs after it dead-letters a command of type
TCommand, so the feature that scheduled the command can record that its work was abandoned (for example, mark the aggregate it was driving as failed) instead of leaving that aggregate waiting forever (IInternalCommandDeadLetterHandler.cs:3-8).Depends on:
IInternalCommand(Level 3, theTCommandconstraint,:35) andInternalCommandDeadLetterNotice(Level 0, the secondHandleAsyncargument). BCLTaskandCancellationToken.Concept introduced, a compensating callback on terminal failure.
[Rubric §29, Reliability and Resilience]assesses whether a retrying queue leaves the system in a known state once it gives up: without a hook, an aggregate whose follow-up work dead-letters stays in its in-flight state with nobody told. The callback closes that gap, and the doc pins its semantics (:10-33): it runs once, after the dead-letter stamp is written under this replica's claim, only for a row whose payload still deserializes asTCommand; it runs in a fresh DI scope with the scheduling user, tenant and correlation id restored, but not through the command pipeline and not in the dead-letter stamp's transaction (:12-17). It is best-effort: an exception is logged and swallowed and never retried, so a callback must be idempotent and cheap and must not schedule more internal commands to make up for the abandoned one (:20-22).[Rubric §1, SOLID](OCP): a feature adds its compensation by registering one more implementation, and the processor needs no change.Walkthrough: one member,
Task HandleAsync(TCommand command, InternalCommandDeadLetterNotice notice, CancellationToken cancellationToken = default)(:42), wherecommandis the abandoned command deserialized from its row andnoticesays why and after how many attempts (:38-39); the token is cancelled on host shutdown (:40).TCommandisin(contravariant), so a handler written for a base command type can serve a derived one. Registration isAddScoped<IInternalCommandDeadLetterHandler<MyCommand>, MyHandler>(), and every registration for the command type runs; one that throws does not stop the others (:30-31). Requeuing the row throughIInternalCommandAdministration.RequeueAsyncruns the command again and does not undo what the callback recorded: a command whose handler can finish the work after a requeue decides itself whether to restore the earlier state (:25-27).Why it's built this way: the processor side matches the contract.
DeadLetterAsyncnotifies only when the stamp succeeded and a typed command exists (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:656-660);NotifyDeadLetterAsyncopens a new scope, restores the row's origin throughAmbientOrigin, and catches and logs any non-cancellation failure asLogDeadLetterCallbackFailedunder a scopedCA1031suppression (:681-713).InternalCommandDispatcherresolvesGetServices<IInternalCommandDeadLetterHandler<TCommand>>()through a per-type cached generic delegate, runs each handler even when an earlier one throws, and rethrows the collected failures together as oneAggregateException(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandDispatcher.cs:76-88, loop at:98-114, rethrow at:116-119), which the processor then logs. ADR-114 is the decision record for the queue.Where it's used: the one shipped implementation is
DeliverPushNotificationPageDeadLetterHandler(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageDeadLetterHandler.cs:28-31), which marks aPushNotificationfailed when one of its delivery pages is dead-lettered, skipping a deleted or already failed notification so it stays idempotent (:42-53). It is registered withTryAddEnumerableforDeliverPushNotificationPageInternalCommand(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:86-89). Covered byInternalCommandDeadLetterCallbackTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/Processing/InternalCommandDeadLetterCallbackTests.cs) andNotificationDependencyInjectionTests.Caveats / not-in-source: a row dead-lettered because its type or payload cannot be read gets no callback at all (
:12-14), so a feature cannot rely on this hook alone to observe every abandoned command of its type; the dead-letter metric andIInternalCommandAdministration.ListDeadLettersAsyncstill see those rows.
IInternalCommandScheduler
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/IInternalCommandScheduler.cs:16· Level 4 · interface
What it is: the write side of the internal-command queue: schedule an
IInternalCommandto run at a future instant or after a delay, instead of running it inline on the current request.Depends on:
IInternalCommand(Level 3, the type every scheduled payload must implement) and, through its return doc,IInternalCommandAdministration(the scheduled id is the handle the administration surface operates on). BCL (DateTimeOffset?,TimeSpan).Concept introduced, transaction-aware durable scheduling.
[Rubric §29, Reliability and Resilience]: scheduling a command is not fire-and-forget the way an in-memoryTask.Delaywould be, it is a database write that must be atomic with whatever aggregate change triggered it. The XML remarks onScheduleAsync(:38-47) state the rule explicitly: with a transaction active on the target data source the row is only enrolled, and the caller's next save writes it; when no save follows (a command scheduled after the handler's last save), the transactional pipeline saves it just before the commit, so it still commits with the aggregate change. That pipeline refuses to commit any other change left unsaved, so a handler cannot lean on it to save its own work (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TransactionalCommandDecorator.cs:16). With no transaction active the row is saved immediately, which flushes anything else pending on that context exactly as the unit of work's own save would.[Rubric §6, CQRS and Event-Driven]: scheduling inside anITransactionalcommand, or right after the caller's own save, is how a scheduled command and the state change that caused it commit or roll back together.Walkthrough: two overloads, both returning
Task<Result<Guid>>where theGuidis the scheduled row's id, the same idIInternalCommandAdministrationlater operates on.ScheduleAsync(IInternalCommand command, DateTimeOffset? runAt = null, CancellationToken cancellationToken = default)(:49-52):runAtis the earliest instant the command may run, converted to UTC;nullor already-past means "as soon as the processor next polls". The processor never runs a row before this instant but makes no promise about how quickly after it a busy queue gets there.ScheduleAsync(IInternalCommand command, TimeSpan delay, CancellationToken cancellationToken = default)(:67-70): schedules afterdelayhas elapsed; a delay of zero or less also means "as soon as possible".- Both return a failure when the row cannot be written; the first overload's return doc also names a payload that cannot be serialized (
:33-37). - Both
commandparameter docs (:22-26,:58-62) require a payload that round-trips through JSON and holds no reference cycle. A cycle, in practice an entity graph placed on the payload, throws aJsonExceptioninstead of returning a failure, because the doc classes it as a modelling error rather than a runtime condition. The instruction is to carry identifiers, not entities. - Both carry a
SuppressMessagefor analyzer ruleRS0026(multiple public overloads with optional parameters) (:48,:66), justified as a grandfathered public overload released after the v1.152 public-API baseline: changing either signature now would be a breaking change.
Why it's built this way: two overloads rather than one nullable-
DateTimeOffsetparameter give the common "run in N minutes" case aTimeSpancall site without the caller doingDateTimeOffset.UtcNow.Add(...)arithmetic itself, while the absolute-instant overload covers "run at this specific time".Where it's used: called wherever a host wants to defer a command, for example ADC's
AuthController(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs),DeleteUserHandler,RemoveUserAvatarHandler,SetUserAvatarHandler(all underMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/), and Conference'sDeleteEventHandler,DeleteSessionAssetHandler,UploadSessionAssetHandler,DeleteSessionHandler(underMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/). ADC'sSessionSelectionController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionSelectionController.cs) also takes it. Implemented byInternalCommandScheduler(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandScheduler.cs) and registered withTryAddScopedinMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:165. Referenced by ADR-024, ADR-054, ADR-086, ADR-114 (the decision record for the internal-command queue itself) and ADR-121.Caveats / not-in-source: the doc's transaction-aware persistence rule is stated in the interface's own XML remarks, not enforced by a compile-time type; a caller that intends transactional enrollment but is not actually inside an
ITransactionalcommand silently gets the immediate-save behavior instead.
DeleteBlobInternalCommandHandlerBase<TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/DeleteBlobInternalCommandHandlerBase.cs:28· Level 5 · class (abstract, partial)
What it is: the reusable handler body for any
IDeleteBlobInternalCommand: delete the named blob, treat "already gone" as success rather than failure, and log every outcome distinctly.Depends on:
IDeleteBlobInternalCommand(Level 4, theTCommandconstraint),ICommandHandler<TCommand, Result>(the contract it implements),IFileStorageService(constructor dependency,DeleteAsync) andErrorType(NotFound, tested against the failure result). Externally,Microsoft.Extensions.Loggingfor its three source-generated[LoggerMessage]methods.Concept introduced, a base class that turns "not found" into a non-failure.
[Rubric §29, Reliability and Resilience]assesses whether a retryable job queue treats an already-completed side effect as success rather than as a reason to retry forever: a blob deleted by an earlier, since-crashed attempt (or removed out of band) must not keep the internal command dead-lettering.HandleAsync(DeleteBlobInternalCommandHandlerBase.cs:41-65) checksresult.Errors.Any(e => e.Type == ErrorType.NotFound)(:53) and returnsResult.Success()in that case (:56) instead of propagating the storage failure.[Rubric §15, Best Practices & Code Quality]: the class isabstract partial, generic overTCommand, and provides one override point,protected virtual string BlobKind => "Blob";(:38), so a concrete handler needs only a class declaration and, optionally, a friendlier log label;DeleteSessionAssetBlobInternalCommandHandlerandDeleteAvatarBlobInternalCommandHandlerboth derive from it with no additional logic of their own.Walkthrough: a primary-constructor class taking
IFileStorageService fileStorageandILogger logger(:49-51), constrainedwhere TCommand : IDeleteBlobInternalCommand(:53).HandleAsync(TCommand command, CancellationToken cancellationToken = default)(:62) null-guards the command (:64), callsfileStorage.DeleteAsync(command.BlobName, cancellationToken)(:66), and branches three ways: success logsLogBlobDeletedand returns the successfulresult(:68-72); aNotFounderror logsLogBlobAlreadyGoneand returnsResult.Success()(:74-78); any other error logsLogBlobDeleteFailedwith the first error's message (or"Unknown error"if the error list is empty,:84) and returns the original failedresult(:80-85). The three[LoggerMessage]partial methods (:88-95) areInformation,Information, andWarningrespectively, each interpolatingBlobKindandBlobNameso the log line reads naturally for whichever concrete command is running.Why it's built this way: factoring the delete-then-tolerate-not-found logic into a shared abstract base means every blob-owning feature gets the same retry-safety guarantee without re-deriving it, and the single
BlobKindoverride point is enough for each concrete handler to produce its own readable log lines without overridingHandleAsyncitself.Where it's used:
DeleteSessionAssetBlobInternalCommandHandler(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/DeleteSessionAssetBlob/DeleteSessionAssetBlobInternalCommandHandler.cs) andDeleteAvatarBlobInternalCommandHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteAvatarBlob/DeleteAvatarBlobInternalCommandHandler.cs) both derive fromDeleteBlobInternalCommandHandlerBase<TCommand>closed over their own command type.Caveats / not-in-source: the class does not itself register as an
ICommandHandler; registration happens through the ordinaryScanModuleApplicationServicesscan picking up each concrete derived handler, not through anything specific to this base class.
AccountProof
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.EmailConfirmation·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:73· Level 0 · enum (private, nested)
What it is: the private enum nested inside
ConfirmEmailHandlerBase<TUser, TCommand>that records how the caller proved the account on a confirmation request that will complete (ConfirmEmailHandlerBase.cs:72-86). Four members:NoPassword, the account holds no password credential so the token is the whole proof (:76);SignedInAsAccount(:79);CurrentPassword(:82); andNewPassword, the caller claimed the account with a new password (:85).Depends on: nothing. It is declared inside its handler and is visible to nothing else.
Concept introduced: none of its own; the "link proves the mailbox, not the account" rule it encodes is taught in
ConfirmEmailHandlerBase<TUser, TCommand>. The enum is the hand-off between deciding and acting: the privateProveAccountAsyncreturns aResult<AccountProof>and changes nothing but the lockout counter (:188-195), andCompleteAsynctakes the proof as a parameter (:155-159) and branches on it twice.Walkthrough: each member maps to one branch of
ProveAccountAsync:NoPasswordwhenTUseris not anIAuthUserorPasswordCredential.IsStoredis false (:200-203);SignedInAsAccountwhen the request principal's user id equals the account's (:205-208);CurrentPasswordwhen the supplied current password verifies (:210-213,:247-249);NewPasswordwhen a new password is supplied andTUserimplementsIPasswordChangeableUser(:215-220). InCompleteAsync,NewPasswordroutes to the account claim instead of a plainuser.ConfirmEmail()(:168-170), andCurrentPasswordorNewPasswordclears the failed-attempt counter after the save (:179-182). The value is also the{Proof}placeholder of theEmailConfirmedWithProofsuccess log (:184,:312-313), so the audit line names which proof completed the confirmation.Why it's built this way: every method that produces or reads it is
private, so the proof decision is not part of the base class's extension surface: a subclass can neither see the enum nor override how an account is proved.Where it's used: only inside
ConfirmEmailHandlerBase.cs. Each member is exercised byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/EmailConfirmation/ConfirmEmailAccountProofTests.cs(for example:127,:193,:249,:276).
IUserScopedRequest
MMCA.Common.Application ·
MMCA.Common.Application.Users·MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserScopedRequest.cs:8· Level 0 · interface
What it is: a one-member shape interface saying "this command or query targets a single user account". It exposes exactly
UserIdentifierType UserId { get; }and nothing else.Depends on: the solution-wide identifier alias
UserIdentifierType(the convention recorded in ADR-048). Nothing else, first-party or external; the file has nousingdirectives at all (IUserScopedRequest.cs:1).Concept introduced, shape interfaces instead of shared request records.
[Rubric §1, SOLID]assesses interface segregation and dependency inversion together, and this is the smallest possible instance of both: the shared Users use-case bases need one fact about the incoming message (which account it addresses), so that fact, and only that fact, becomes the contract. The XML doc states the motivation directly (IUserScopedRequest.cs:3-7): each app keeps its own command or query record, with its ownICacheInvalidatingchoice and its own docs, and simply adds this interface.[Rubric §15, Best Practices & Code Quality]: hoisting the behavior into a base class while leaving the record app-side is what let ADC and Store share the handlers without either app losing a per-app pipeline decision.Walkthrough: a single interface with a single get-only property (
IUserScopedRequest.cs:11). There is no base interface and no default member, so implementing it is free for arecordthat already has aUserIdpositional parameter.Where it's used: extended by
IUserOwnedRequestandIUserScopedCommand<out TRequest>, both Level 1 in this chapter. Implemented directly by the one shared query record in the framework,GetUserPreferencesQuery(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesQuery.cs:5), which is the only implementer inside MMCA.Common.
ApplicationSettings
MMCA.Common.Application ·
MMCA.Common.Application.Settings·MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ApplicationSettings.cs:8· Level 0 · class (sealed)
What it is: the framework's global settings object, bound from the
"ApplicationSettings"configuration section, with four knobs:UseMiniProfiler(MiniProfiler tracing),MaxPageSize(the ceiling the API applies to a paged list query),MaxExportRows(the ceiling on a single CSV export) andDatabaseInitStrategy("Migrate"or"None").Depends on: nothing first-party.
System.ComponentModel.DataAnnotationsfor one[Range]attribute (ApplicationSettings.cs:1,:32), and the options binder at the composition root. That purity is why it sits at Level 0 despite being reachable from nearly every layer.Concept introduced, options-pattern settings classes.
[Rubric §17, DevOps & Deployment]assesses whether configuration is centralised and typed rather than read as magic-string keys scattered through the codebase. Every settings class in the framework follows the same three-part shape, and this is the simplest exemplar of it: apublic static readonly string SectionNamenaming the configuration section (ApplicationSettings.cs:11) so no registration site spells the section out,init-only properties so the object is immutable once the binder has filled it, and defaults declared inline beside the property. Consumers takeIOptions<ApplicationSettings>from the container or receive the bound instance by value; nothing injectsIConfigurationto read these values.[Rubric §8, Data Architecture]shows up in the last knob:"Migrate", the default, applies pending EF Core migrations at startup in every environment, production included, and is multi-replica safe because replicas serialize on EF's migrations lock under a raised command timeout;"None"is the posture for a deployment that applies migrations out of band, and it validates and fails startup when the schema is behind rather than migrating it (:35-45).[Rubric §12, Performance and Scalability]is why the two ceiling knobs exist at all: both stop one caller from turning a single request into a full-table scan.Walkthrough:
SectionName = "ApplicationSettings"(:11).UseMiniProfilertakes the implicitfalsedefault (:14).MaxPageSize = 500(:17).MaxExportRows = 100_000(:33) is the one property carrying a validation attribute,[Range(1, 10_000_000)](:32), and its remarks explain both the number and the attribute's limits (:24-31): 100,000 rows is roughly a 10 to 25 MB file for a typical grid DTO, large enough that no real operational export hits the cap and small enough that one caller cannot pin a request thread to a full-table scan; the[Range]is honored only by hosts that opt intoValidateDataAnnotationson the options binding, so the export endpoint independently falls back to its own default when a host configures a non-positive value. The two ceilings compose rather than duplicate: the export endpoint page-loops the query service atMaxPageSizeper page, soMaxExportRowsbounds the whole file and not one page (:19-23).DatabaseInitStrategy = "Migrate"(:46).Why it's built this way:
static SectionNamekeeps registration DRY, andinitimmutability makes one bound instance safe to share across the process as a singletonIOptions<T>value and safe to hand to every module by value. Validating a bound value with an attribute rather than a hand-written guard keeps the ceiling declarative, while the endpoint-side fallback means a host that never opts into validation still cannot produce an unbounded export.Where it's used: bound and validated by
ModuleHostExtensions.AddModuleHost, which callsAddOptions<ApplicationSettings>().Bind(...).ValidateDataAnnotations().ValidateOnStart()and then reads the section a second time to get a plain instance, throwing when the section is absent (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostExtensions.cs:61-67). That instance is carried onModuleHostContext.ApplicationSettings(ModuleHostContext.cs:41) and passed by value into everyIModule.Register(services, configuration, applicationSettings)call, so a module reads global settings without resolving anything. Each knob then has a distinct consumer:MaxPageSizeis resolved per request byEntityControllerBase<TEntity, TEntityDTO, TIdentifierType>throughIOptions<ApplicationSettings>with a500fallback when nothing is registered (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:58-64);MaxExportRowsthe same way, withDefaultMaxExportRows = 100_000(EntityControllerBase.cs:526) used both when no settings exist and when a host configures a non-positive value (:78-85,:290, ADR-078);UseMiniProfilergatesMiniProfilerExtensions(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/MiniProfilerExtensions.cs:28) and the profiling repository wrappers inRepositoryFactory(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:34,:58);DatabaseInitStrategydrives the startup switch inDatabaseInitializationExtensions(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:120-130), where"Migrate"callsMigrateAsyncand"None"throws when any source has pending migrations; an unknown value is refused up front byEnsureKnownStrategy(:63,:294-295) with an exception naming the two valid ones (:305).
ModuleSettings
MMCA.Common.Application ·
MMCA.Common.Application.Settings·MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ModuleSettings.cs:6· Level 0 · class (sealed)
What it is: the per-module configuration entry bound from
Modules:{Name}inappsettings.json.Enabled(defaulttrue) controls whether the module's service tree is registered;RemoteDependencieslists dependency module names that are satisfied by an extracted remote service rather than an in-process module.Depends on: BCL only (
List<string>plus the options binder).Concept introduced, the module-extraction boundary expressed as configuration.
[Rubric §7, Microservices Readiness]assesses whether a module can be lifted into its own service without rewriting application code. ADR-008 is the why: when Catalog is extracted, the host sets"Catalog": { "Enabled": false }, and any module that still depends on it adds"RemoteDependencies": [ "Catalog" ].ModuleLoaderthen treats that dependency as satisfied, lets the disabled module'sRegisterDisabledStubsput the contract type into DI, and the host afterwards replaces the stub with a real gRPC client adapter. The XML doc walks exactly this Catalog/Sales example, including the sample JSON (ModuleSettings.cs:11-36). Extraction therefore becomes a configuration plus wiring change, not a code change.Walkthrough:
bool Enabled { get; init; } = true(ModuleSettings.cs:9),init-only so it cannot be mutated after binding.List<string> RemoteDependencies { get; set; } = [](:37), and note this one isset, notinit, because theIConfigurationbinder needs a settable collection to populate. No inline suppression is needed:CA2227("collection properties should be read only") is switched off repo-wide inMMCA.Common/.editorconfig:352-353, whose comment gives the same reason (DTOs and bound settings need setters).Why it's built this way: a plain POCO bound by the options pattern keeps the configuration model decoupled from the module infrastructure, and the
Enabledflag lets a deployment switch off a whole module without deleting code.Where it's used: as the value type of
ModulesSettings(the"Modules"dictionary), read for every discoveredIModulebyModuleLoaderduring composition, and enumerated directly byModuleControllerFeatureProviderwhen it filters out the controllers of disabled modules (MMCA.Common/Source/Presentation/MMCA.Common.API/ModuleControllerFeatureProvider.cs:36-39).
QueryCachePipelineSettings
MMCA.Common.Application ·
MMCA.Common.Application.Settings·MMCA.Common/Source/Core/MMCA.Common.Application/Settings/QueryCachePipelineSettings.cs:20· Level 0 · class (sealed)
What it is: the Application layer's narrow view of the
Cacheconfiguration section, carrying exactly one knob: how long a request that missed the cache waits for the per-key populate lock before giving up and running the handler uncached.Depends on: BCL only (
TimeSpan). Bound by Infrastructure, read byCachingQueryDecorator<TQuery, TResult>.Concept introduced, splitting one configuration section across two layers without a layer violation.
[Rubric §3, Clean Architecture]assesses whether the dependency rule survives contact with real configuration. The rest of theCachesection (TTL policy, key prefix) is bound in Infrastructure besideCacheSettings, but the caching decorator lives in the Application layer, and Application cannot reference Infrastructure. Rather than duplicating a settings class or pushing the decorator down a layer, the framework declares this one-property class in Application and lets Infrastructure bind it: both types read the sameCache:PopulateLockTimeoutkey, so they cannot drift (QueryCachePipelineSettings.cs:3-14, and the reciprocal note onCacheSettingsatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheSettings.cs:21).[Rubric §12, Performance & Scalability]: the sameSectionNameplusinitshape as every other settings class here (ApplicationSettingsintroduces it).[Rubric §12, Performance and Scalability]: the knob exists for cache-stampede control, and the five-second default keeps that protection for a normal populate while a wedged populate degrades its waiters to uncached reads instead of queueing them indefinitely (:25-30).[Rubric §29, Resilience and Business Continuity]: the remarks call the behavior fail-open outright, "the value bounds how long a request waits, never whether it succeeds" (:16-18), which is the same posture every other cache failure takes in this framework.Walkthrough:
SectionName = "Cache"(:23), the same section Infrastructure's own cache settings bind to.DefaultPopulateLockTimeout = TimeSpan.FromSeconds(5)(:30), astatic readonlyso the settings object, a hand-constructed decorator and Infrastructure'sCacheSettingsdefault (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheSettings.cs:84) all reach the same fallback.TimeSpan PopulateLockTimeout { get; init; } = DefaultPopulateLockTimeout(:43). The remarks spell out the trade (:36-42): within the wait exactly one request per key populates the entry and the rest are served from it; once the wait elapses the waiter proceeds uncached, so a pathologically slow populate cannot hold a queue behind it, at the cost of several requests running the same query at once. Zero or a negative value means no bound: waiters block until the populate finishes.Why it's built this way: keeping the knob in Application is what lets
CachingQueryDecoratortake it as a constructor dependency at all, and making the fallback astatic readonlyon the settings type is what lets the decorator's optionalIOptions<>parameter degrade cleanly to framework behavior in a unit test or in a host that never calledAddCaching.Where it's used: bound by Infrastructure's
AddCachingpath, with validation when a configuration is supplied (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:58-61) and as a bareAddOptions<T>()when it is not, soIOptions<QueryCachePipelineSettings>always resolves to the framework defaults rather than failing the host (:61, comment at:38-43). Read byCachingQueryDecorator<TQuery, TResult>, which takes it as an optional constructor parameter (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:48), falls back toDefaultPopulateLockTimeoutwhen it is absent (:84-85), and on a lock timeout logs, records a cache miss and runs the inner handler without caching the result (:87-96). Pinned byCacheSettingsTests, which asserts that the Infrastructure and Application views share one finite default (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Settings/CacheSettingsTests.cs:35-37) and that the bound and unbound registrations resolve (:101,:117-118).
IUserOwnedRequest
MMCA.Common.Application ·
MMCA.Common.Application.Users·MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserOwnedRequest.cs:8· Level 1 · interface
What it is:
IUserScopedRequestplus the authenticated caller. It addsCurrentUserIdand the caller's (nullable) role claim, which is exactly the input the shared owner-or-privileged-role check needs.Depends on:
IUserScopedRequest(Level 0, its base interface,IUserOwnedRequest.cs:8) and theUserIdentifierTypealias.Concept introduced, carrying the caller inside the message.
[Rubric §11, Security]assesses whether authorization decisions are made deliberately and consistently rather than ad hoc. In this codebase resource-ownership authorization exists on two levels: at the API level as an action filter plus a specification (ADR-033), and at the handler level as this interface plusUserOwnershipRule. The controller projects the caller's claims into the command or query, and the handler decides. Putting the caller in the message rather than injecting a current-user service into the handler keeps the handler a pure function of its input, which is what makes the shared bases unit-testable with no HTTP context ([Rubric §14, Testability]).Walkthrough: two added members.
UserIdentifierType CurrentUserId { get; }(IUserOwnedRequest.cs:11) is the authenticated caller.string? CurrentUserRole { get; }(IUserOwnedRequest.cs:18) is the role claim, explicitly nullable because a token may carry no role at all. Its XML doc (IUserOwnedRequest.cs:13-17) fixes which claim a caller passes: the first role claim, which is the only one on the single-role tokens the framework mints, while a host that issues multi-role tokens passes its privileged role whenever the caller holds it.UserIdis inherited, so an implementing record must expose both the target and the caller.Why it's built this way: the XML doc names the goal (
IUserOwnedRequest.cs:3-7), a single uniformly applied owner-or-privileged-role check across the account-deletion and data-export use cases in both apps. The role itself is deliberately not interpreted here: each app owns its own role vocabulary, so the interface carries the raw claim string and the rule takes an already-evaluated boolean.Where it's used: the type constraint on all three consumers of the ownership rule:
DeleteUserHandlerBase<TUser, TCommand>(.../DeleteUser/DeleteUserHandlerBase.cs:42),ExportUserDataHandlerBase<TUser, TQuery>(.../ExportUserData/ExportUserDataHandlerBase.cs:55), and the API-layerDataExportControllerBase<TQuery>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:64). It is also the parameter type ofUserOwnershipRule.CheckOwnership. Implemented app-side by each export query (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataQuery.cs:12,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataQuery.cs:13) and by each delete command, both of which pair it withICacheInvalidating(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserCommand.cs:13,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/DeleteUser/DeleteUserCommand.cs:17).
IUserScopedCommand<out TRequest>
MMCA.Common.Application ·
MMCA.Common.Application.Users·MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserScopedCommand.cs:14· Level 1 · interface
What it is:
IUserScopedRequestplus an embedded request payload. A command implementing it says "I target this user, and here is the DTO the caller sent".Depends on:
IUserScopedRequest(Level 0, its base interface). Nothing external.Concept, covariant shape interfaces and the deliberate non-overlap with
ICommandWithRequest<TRequest>. The type parameter is declaredout TRequest(IUserScopedCommand.cs:14), soIUserScopedCommand<DerivedRequest>is usable whereIUserScopedCommand<BaseRequest>is expected. The more instructive part is the XML doc's warning (IUserScopedCommand.cs:6-12): this interface is deliberately separate fromICommandWithRequest<out TRequest>, even though both expose aRequestproperty, becauseICommandWithRequestalso opts the command into automaticCommandRequestValidator<TCommand, TRequest>registration (seeScanModuleApplicationServicesinDependencyInjection,MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:84-96). That is a per-app decision: ADC and Store agree on it for the password change and disagree on it for preferences. A command may implement both; implementing this one alone changes no pipeline behavior.[Rubric §1, SOLID]: two interfaces because there are two responsibilities, shape versus pipeline opt-in, even though they would collapse neatly into one.Walkthrough: one added member,
TRequest Request { get; }(IUserScopedCommand.cs:17), on top of the inheritedUserId.Why it's built this way: the split is what lets one shared handler base read any app's command uniformly while each app keeps its own validation and cache-invalidation posture. Store's change-password command implements both interfaces (
MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:13) while its preferences command implements only this one (.../ChangePreferences/ChangePreferencesCommand.cs:12); ADC's equivalents have the same shape, with noICacheInvalidating(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:13,.../ChangePreferences/ChangePreferencesCommand.cs:12).Where it's used: the constraint on
ChangePasswordHandlerBase<TUser, TCommand>(.../ChangePassword/ChangePasswordHandlerBase.cs:29) andChangePreferencesHandlerBase<TUser, TCommand>(.../ChangePreferences/ChangePreferencesHandlerBase.cs:27), and the two constraints onUserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:48-49), where the base reads the app-supplied command back only through this interface and its own doc records that the preferences query has no equivalent marker (UserAccountAuthControllerBase.cs:29).
ModulesSettings
MMCA.Common.Application ·
MMCA.Common.Application.Settings·MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ModulesSettings.cs:8· Level 1 · class (sealed)
What it is: a
Dictionary<string, ModuleSettings>subclass bound from the"Modules"configuration section, with two helper methods over the map:IsModuleEnabled(moduleName)andIsDependencyRemote(consumerModule, dependencyModule).Depends on:
ModuleSettings(Level 0, the entry/value type).Concept: the same options-pattern shape, but realised by subclassing the dictionary so
appsettings.jsoncan express an arbitrary map of module name to settings without a hand-written model class per module.[Rubric §7, Microservices Readiness]:IsDependencyRemoteis the extracted-service hook, and when a module's dependency is met by a remote service rather than an in-process module, it returns true andModuleLoadertreats the dependency as satisfied.Walkthrough:
SectionName = "Modules"(ModulesSettings.cs:11). The parameterless constructor passesStringComparer.OrdinalIgnoreCaseto the base dictionary (:18-21), soModules:catalogand a module namedCatalogare the same entry; configuration binding creates the instance through that constructor and keeps the comparer (:13-17), which makes key lookup match module names the same case-insensitive wayModuleLoaderdoes.IsModuleEnabled(:29-30) isTryGetValuefollowed bysettings.Enabled, so a module absent from configuration is treated as disabled, not enabled, which the XML doc states explicitly (:23-26).IsDependencyRemote(:41-43) doesTryGetValuefor the consumer, thensettings.RemoteDependencies.Contains(dependencyModule, StringComparer.OrdinalIgnoreCase), case-insensitive so deployment configuration need not match casing exactly.Why it's built this way: subclassing
Dictionary<,>rather than wrapping one keeps the binder's job trivial (the section is literally a map) while still giving the two questions the loader asks a named, testable home instead of leavingTryGetValuechains scattered through composition code.Where it's used: bound beside
ApplicationSettingsbyModuleHostExtensions.AddModuleHost, eagerly and never registered asIOptions<ModulesSettings>(nothing resolves it and the type carries no annotations, so it is not validated), falling back to an empty map when the section is absent (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostExtensions.cs:69-73); the host carries it onModuleHostContext(ModuleHostContext.cs:44). Consumed byModuleLoaderfor both the enable check and the remote-dependency bypass (ModuleLoader.cs:116,:133,:137), and byModuleControllerFeatureProviderto keep MVC from mapping a disabled module's controllers (MMCA.Common/Source/Presentation/MMCA.Common.API/ModuleControllerFeatureProvider.cs:28-29,:36-41); it is also the optional first parameter ofAddAPI(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:45).
UserOwnershipRule
MMCA.Common.Application ·
MMCA.Common.Application.Users·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserOwnershipRule.cs:20· Level 2 · class (static)
What it is: a single static method encoding the self-service authorization rule shared by every use case that acts on one account on behalf of its owner: the caller must be the account owner, or hold the app's privileged role. It returns
nullwhen allowed and a ready-madeErrorwhen not.Depends on:
IUserOwnedRequest(Level 1, the parameter type), plusErrorandErrorTypefromMMCA.Common.Shared.Abstractions(imported atUserOwnershipRule.cs:1).Concept introduced, the "return the error, do not throw" authorization helper.
[Rubric §11, Security]assesses whether authorization is uniform and auditable. The idiom being hoisted here (caller is not the owner and has no bypass role, therefore forbidden) had been written out four times across the two apps, in account deletion and data export in each, which the XML doc records as the motivation (UserOwnershipRule.cs:9-14).[Rubric §2, Design Patterns]: it is deliberately a plain static helper, not a base class or a decorator, because at the time of the hoist the two data-export handlers were expected to stay app-level and still needed the identical decision and the identical error shape.[Rubric §1, SOLID]: the role test arrives already evaluated as abool, so the helper never learns either app's role vocabulary (UserRole.IsAdmin, or whatever the app's privileged role is), and every such test is case-insensitive on the app side because a role claim may carry any casing (UserOwnershipRule.cs:14-18). This is the Application-layer counterpart to the API-layer ownership axis of ADR-033; that ADR records the filter and specification forms and does not name this helper.Walkthrough: one method,
static Error? CheckOwnership(IUserOwnedRequest request, bool callerHasPrivilegedRole, string code, string message, string source)(UserOwnershipRule.cs:37-42). It guards withArgumentNullException.ThrowIfNull(request)(:45), then evaluates one conditional expression: ifrequest.CurrentUserId == request.UserId || callerHasPrivilegedRole, returnnull(allowed); otherwise returnError.Forbidden(...)with the caller-suppliedcode,message, andsource, and withtargetfixed tonameof(IUserOwnedRequest.UserId)(:47-53). Fixing the target while parameterising code, message, and source is what keeps the error payload identical to the four hand-written copies it replaced, since each of those reported its own handler name as the source.Why it's built this way: returning
Error?rather than throwing keeps the caller on the framework's Result pattern (ADR-013): the handler wraps it asResult.Failure(forbidden)and the API layer maps it to 403 through the usual error mapping, with no exception unwinding on an expected authorization outcome.Where it's used: both shared account-scoped bases call it first thing in
HandleAsync.DeleteUserHandlerBase<TUser, TCommand>passesHasDeletePrivilege(command.CurrentUserRole)and the code"User.DeleteForbidden"with the message "You can only delete your own account." (.../DeleteUser/DeleteUserHandlerBase.cs:62-67);ExportUserDataHandlerBase<TUser, TQuery>passesHasExportPrivilege(query.CurrentUserRole)and the code"User.ExportForbidden"with the message "You can only export your own account data." (.../ExportUserData/ExportUserDataHandlerBase.cs:81-86). Both pass their ownHandlerNameas the source, so the error still names the concrete app handler.
UserEmailLookup
MMCA.Common.Application ·
MMCA.Common.Application.Users·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:18· Level 6 · class (static)
What it is: the one find-the-account-by-address read the shared identity workflows use: password sign-in in
AuthenticationServiceBase<TUser>, forgot password, the email-confirmation send and both sign-in-link workflows (UserEmailLookup.cs:9-13). It has two members: a public translatable predicate,HasEmail<TUser>, and an internal extension method,FindUntrackedByEmailAsync<TUser>, that runs that predicate through a repository.Depends on:
IEmailIdentifiedUser(the constraint that gives the account type its address,UserEmailLookup.cs:3,:29), theEmailvalue object (:5),IEntityQuerier<TEntity, TIdentifierType>(the receiver of the extension,:2,:39) andAuditableBaseEntity<TIdentifierType>(the second constraint on that method,:4,:42); externallySystem.Linq.Expressions(:1).Concept introduced, one predicate written against an interface member that EF still translates.
[Rubric §15, Best Practices & Code Quality]: five workflows need the same "which account holds this address" read, so the predicate is written once, againstIEmailIdentifiedUser.Emailon a generic account type rather than against each app's concreteUser, and the account type supplies only its address (UserEmailLookup.cs:10-12).[Rubric §8, Data Architecture]: an expression over an interface member is only useful if EF binds it to the aggregate's own mapped column; the doc onHasEmailstates that it does, so the predicate translates to SQL and an app's own existence check can reuse it (:20-23).[Rubric §11, Security]: the read keeps the soft-delete filter, so an erased or deleted account is never found by its old address (:15-16).Walkthrough:
HasEmail<TUser>(Email? email)is constrainedwhere TUser : class, IEmailIdentifiedUserand returnsuser => user.Email == emailas anExpression<Func<TUser, bool>>(UserEmailLookup.cs:28-30); anulladdress matches no account (:26).FindUntrackedByEmailAsync<TUser>isinternal, so only the framework's own workflows call it: it extends anIEntityQuerier<TUser, UserIdentifierType>, constrainsTUsertoAuditableBaseEntity<UserIdentifierType>, IEmailIdentifiedUser, and returnsusers.FirstOrDefaultAsync(HasEmail<TUser>(email), asTracking: false, ...)directly (:38-43). The read is untracked because the workflows re-fetch the account tracked by id before changing it (:15).Why it's built this way: a static helper over an interface constraint keeps the framework free of any reference to an app's
Useraggregate while still producing an equality on the stored column, and keeping the repository methodinternalleavesHasEmailas the only public surface an app can reuse.Where it's used:
GetReadRepository<TUser, UserIdentifierType>().FindUntrackedByEmailAsync(...)is the lookup step inAuthenticationServiceBase(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:187-190),ForgotPasswordHandlerBase<TUser, TCommand>(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:114-117),SendEmailConfirmationHandlerBase<TUser, TCommand>(.../EmailConfirmation/SendEmailConfirmationHandlerBase.cs:115),SendSignInLinkHandlerBase<TUser, TCommand>(.../SignInLinks/SendSignInLinkHandlerBase.cs:119) andRedeemSignInLinkHandlerBase<TUser, TCommand>(.../SignInLinks/RedeemSignInLinkHandlerBase.cs:187). Pinned in two halves:UserEmailLookupTestscompiles the predicate and checks the normalized-address andnullcases in memory (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/Lookup/UserEmailLookupTests.cs:26,:35), andUserEmailLookupTranslationTestsruns it on a real SQLite database (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/UserEmailLookupTranslationTests.cs:39,:48-50) and asserts the SQL Server query is an equality on the storedEmailcolumn (:61-65).
SoftDeletedUserValidator<TUser>
MMCA.Common.Application ·
MMCA.Common.Application.Users·MMCA.Common/Source/Core/MMCA.Common.Application/Users/SoftDeletedUserValidator.cs:20· Level 8 · class (sealed, generic)
What it is: the one shared implementation of
ISoftDeletedUserValidator. It answers a single question, "does a row for this user exist and is it soft-deleted", in one query that deliberately bypasses the global soft-delete query filter.Depends on:
ISoftDeletedUserValidator(the interface it implements, fromMMCA.Common.Application.Interfaces.Infrastructure.Auth, imported atSoftDeletedUserValidator.cs:1),IUnitOfWork(injected via primary constructor),IRepository<TEntity, TIdentifierType>(obtained from the unit of work), andAuditableAggregateRootEntity<TIdentifierType>as theTUserconstraint (SoftDeletedUserValidator.cs:3,:20). Its Level 8 position is inherited from that repository and unit-of-work chain, not from any complexity of its own.Concept introduced, closing a generic over the app's aggregate instead of subclassing.
[Rubric §11, Security]assesses whether a revoked principal actually loses access: stateless JWT means a token stays valid until it expires, so ADR-047 (BR-133, named in the class doc atSoftDeletedUserValidator.cs:8) adds a middleware that rejects an authenticated caller whose account has since been soft-deleted, and this class is the lookup behind it.[Rubric §8, Data Architecture]: the check must see rows the rest of the application cannot, so it passesignoreQueryFilters: trueto punch through the soft-delete global filter for this one predicate.[Rubric §15, Best Practices & Code Quality]: because the type is generic overTUserrather than abstract, an app supplies only a type argument at registration and needs no per-app subclass (SoftDeletedUserValidator.cs:12-18).Walkthrough: a primary-constructor class taking
IUnitOfWork unitOfWork, constrainedwhere TUser : AuditableAggregateRootEntity<UserIdentifierType>(SoftDeletedUserValidator.cs:20-21). The single methodTask<bool> IsUserSoftDeletedAsync(UserIdentifierType userId, CancellationToken cancellationToken = default)(:23-25, notasync) resolves the repository throughunitOfWork.GetRepository<TUser, UserIdentifierType>()(:27), then returns the repository task directly,repository.ExistsAsync(u => u.Id == userId && u.IsDeleted, ignoreQueryFilters: true, cancellationToken: cancellationToken)(:30-33), with noawaitand so no extra state machine. Note it isGetRepositoryoff the unit of work rather than a constructor-injectedIRepository<,>, which is the framework-wide rule for repository access, and the predicate is written against the open type parameter but closes over the concrete entity at run time, so EF translates it exactly as a hand-written app query would.Why it's built this way: one query answers both halves of the question (exists and is deleted), so the middleware pays a single round trip and cannot mistake "unknown user" for "deleted user" (
SoftDeletedUserValidator.cs:30). Expressing the predicate againstTUserkeeps the framework free of any reference to an app'sUseraggregate while still producing a fully translated EF query.Where it's used: registered per app, closed over that app's
Useraggregate:services.TryAddScoped<ISoftDeletedUserValidator, SoftDeletedUserValidator<User>>()inMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:37andMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:43. The consumer isSoftDeletedUserMiddleware, which resolves the interface lazily per request viacontext.RequestServices.GetService<ISoftDeletedUserValidator>()(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/SoftDeletedUserMiddleware.cs:117, rationale in its own doc at:43), so a host that registers no validator degrades to a no-op instead of failing. Each app also pins the behaviour directly, across the deleted, live, unknown, and cancellation cases (MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/SoftDeletedUserValidatorTests.cs:14, tests at:26,:42,:58, and:74).
SendEmailConfirmationHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.EmailConfirmation·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/SendEmailConfirmationHandlerBase.cs:64· Level 8 · class (abstract)
What it is: the shared send-a-confirmation-link workflow, split across two executions of the same command. The inline dispatch only schedules the command as an internal command and answers
Result.Success(); the scheduled execution (whether the inline dispatch or the app's registration flow scheduled it) parses the address, resolves the account, skips an already-confirmed address, mints a single-use token and emails it (SendEmailConfirmationHandlerBase.cs:19-24,:64,:81-88). It is the same two-path shape asForgotPasswordHandlerBase<TUser, TCommand>.Depends on:
IUnitOfWork,IEmailConfirmationTokenService,IEmailSender,IInternalCommandScheduler,IOptions<EmailConfirmationSettings>and anILogger(:64-70); implementsICommandHandler<in TCommand, TResult>overResult(:70).TUseris anAuditableAggregateRootEntity<TIdentifierType>keyed byUserIdentifierTypethat implementsIEmailIdentifiedUser(:71), the address the framework'sUserEmailLookupfinds the account by (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:38-43); the constraint requires no confirmation capability.TCommandis anICommandWithRequest<out TRequest>carrying aSendEmailConfirmationRequestand also anIInternalCommand(:72), named with anInternalCommandNameAttribute(:54-57). Also uses theEmailvalue object, readsInternalCommandExecution.IsActiveto pick the path (:85), and logs through four private source-generated[LoggerMessage]methods (:210-222), hence thepartialdeclaration (:64).Concept introduced: an optional capability check with a safe default. Unlike
ConfirmEmailHandlerBase<TUser, TCommand>, which constrainsTUsertoIEmailConfirmableUser, this base does not: itsIsAlreadyConfirmedhook pattern-matches the aggregate against the interface at runtime and answersfalsewhen it is not implemented (user is Domain.Auth.IEmailConfirmableUser { IsEmailConfirmed: true },:159-160), so an app that has not adopted the confirmation contract still gets a working send workflow rather than a generic constraint it cannot satisfy.[Rubric §11: Security]assesses account-enumeration resistance, the same concernForgotPasswordHandlerBase<TUser, TCommand>closes for password resets, and closes it the same way: the inline dispatch never looks the address up. It writes one queue row and answers success (:91-101), so neither the response nor its timing depends on whether the address holds an account (class remarks:27-32). Only the request validator can produce a 400, and a failure to write the queue row, which does not depend on the address, is returned after an Error-levelEmailConfirmationScheduleFailedline (:94-98,:213-214). The rejection log,EmailConfirmationRejected, carries a reason and never an address or account id (:219-222); onlyEmailConfirmationRequested(:210-211) and the Warning-levelEmailConfirmationDeferred(:216-217), both reached after an account resolved, log a user id.Concept introduced: success-always applies to callers, not to the durable queue. The scheduled execution (ADR-114) has no anonymous caller to leak to, and acknowledging a transient fault would lose the mail the queue exists to guarantee (
:35-38). A throttle refusal logsEmailConfirmationDeferredand returnsResult.Failure(tokenResult.Errors)(:131-139), because earlier attempts that failed to send still count against the per-address window, so a registration's row must not drop the mail on a refusal (:38-40). A send failure propagates rather than being caught (:141-146), so the processor logs it with the stack and retries the row with backoff, dead-lettering it visibly if it never clears. The permanent outcomes (malformed address:106-111, no account:113-121, already confirmed:123-129) still succeed, which keeps the at-least-once execution idempotent, and a retry issues a fresh token that replaces the undelivered one; the token is never issued inline, so a queue row never carries the raw credential (:41-43).Walkthrough: two protected properties, the handler method, two private paths, and four hooks (mirroring
ForgotPasswordHandlerBase<TUser, TCommand>member for member, plus the already-confirmed check).UnitOfWork(:75) andSettings(:78).HandleAsync(TCommand, CancellationToken)(:81-88): null-guard (:83), thenInternalCommandExecution.IsActivepicksSendAsyncorScheduleAsync(:85-87).ScheduleAsync(:91-101): private; schedules the command, logging and returning a scheduling failure (:94-98).SendAsync(:104-150): private.Email.Createon the raw string, unwrapped withTryGetValue(:106-111); the untracked lookup through the framework'sUserEmailLookupFindUntrackedByEmailAsyncextension (:113-116), so the base declares no abstract lookup; the already-confirmed short-circuit, a no-op rather than a re-send because a live token for a confirmed address is one more redeemable secret in flight (:123-129);tokenService.IssueAsync, its token read throughTryGetValue, with the throttle deferral (:131-139); oneUserEmailResources.InRecipientCulture(user, ...)call that runsComposeSubject()andComposeBody(ComposeConfirmationLink(...), token)under the account's stored culture (:143-145), followed bySendAsyncwith no surroundingtry(:146); and theEmailConfirmationRequestedlog and success (:148-149).IsAlreadyConfirmed(TUser)(:159-160):protected virtual, the pattern-match default described above.ComposeSubject()(:168):protected virtual,UserEmailResources.Get("EmailConfirmation.Subject"), resolved in the recipient's culture (the account's stored preference, or the request's culture when it has none), so an override is only needed to rebrand.ComposeBody(string?, string)(:178-189) andComposeConfirmationLink(string, string)(:205-208):protected virtual, carrying both the link and the raw token for the same no-deep-linking (MAUI) reason as the password-reset base (:171-173). The body's visible strings (link text, intro, the code-with-expiry line viaUserEmailResources.Plural, the ignore notice) areUserEmailResourceslookups, with the link and the tokenWebUtility.HtmlEncoded (:183,:187). LikeForgotPasswordHandlerBase<TUser, TCommand>.ComposeResetLink, the link rides the address and token in the URL fragment rather than the query string for the same ingress-log andRefererreasons (:199-204).
Why it's built this way: it is the send half of the same email-verification vertical whose confirm side is
ConfirmEmailHandlerBase<TUser, TCommand>, and it repeats the schedule-inline, send-deferred shape ofForgotPasswordHandlerBase<TUser, TCommand>because both are anonymous-reachable endpoints where a differing response would be an enumeration oracle. The two differ on purpose in one place: a password-reset row completes on a throttle refusal, while a confirmation row fails and retries, because a registration flow also schedules this command and its mail must not be dropped (:38-40).Where it's used: subclassed by ADC (
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendEmailConfirmation/SendEmailConfirmationHandler.cs). Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/EmailConfirmationHandlerBaseTests.cs.Caveats: the base never calls
SaveChangesAsyncitself; the queue row is written byIInternalCommandScheduler, and the unit of work is present only for the untracked account read (:113-115), the same caveatForgotPasswordHandlerBase<TUser, TCommand>carries.
ConfirmEmailHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.EmailConfirmation·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:63· Level 9 · class (abstract)
What it is: the shared complete-an-email-confirmation workflow: check the single-use token without spending it, resolve the account it was issued to, require a proof of the account when that account holds a password, then spend the token, let the aggregate mark itself confirmed, and persist (
ConfirmEmailHandlerBase.cs:14-18,:63,:98-144). An already-confirmed address is a success that changes nothing on the aggregate.Depends on:
IUnitOfWork,IEmailConfirmationTokenService, anILogger,ICurrentUserServiceandIAccountClaimService(:64-68); implementsICommandHandler<in TCommand, TResult>overResult(:68). Constraints:TUseris anAuditableAggregateRootEntity<TIdentifierType>keyed byUserIdentifierTypeand implementingIEmailConfirmableUser(:69), andTCommandis anICommandWithRequest<out TRequest>carrying aConfirmEmailRequest(:70). Also usesEmailConfirmationErrors,PasswordCredentialwithIAuthUser(:200), andIPasswordChangeableUser(:217,:268); nests the privateAccountProofenum (:73-86); and logs through six private source-generated[LoggerMessage]methods (:309-327), hence thepartialdeclaration (:63).Concept introduced: the link proves the mailbox, not the account. Anyone can open an account under an address they do not read, so when the unconfirmed account holds a password credential the token alone confirms nothing (class remarks
:27-29). The confirmation completes only when the caller ALSO is signed in as that account (the request principal's user id equalsuser.Id,:205-208), supplies its current password and it verifies under the same lockout accounting a password sign-in uses (:210-213,:239-250), or supplies a new password that claims the account: every refresh session is revoked, any enrolled second factor is removed and the new password replaces the old one (:215-220,:262-282, remarks:35-37). Otherwise the answer isEmailConfirmationErrors.PasswordRequired(HandlerName)and nothing changes (:227-228). An account with no stored password credential, or aTUserthat is not anIAuthUser, is confirmed by the token alone (:200-203). The ADR-116 revision records the rule (ADR-116).Concept introduced: check, then spend. The token is first checked with
ValidateAsync, not spent, so a request that ends inPasswordRequired, a wrong password or a lockout leaves the token redeemable and the page can ask for a password and post again; a wrong token still counts against the attempt cap (:104-108). It is spent throughSpendTokenAsynconly once the request will complete, BEFORE anything is saved (:162-166,:176), matchingResetPasswordHandlerBase<TUser, TCommand>: a token left live until the write succeeds would open a replay window (remarks:45-49).SpendTokenAsynccallsValidateAndConsumeAsyncand additionally requires the spent token to resolve to the same account the check resolved, so a token replaced or spent in between gets the generic invalid-token error (:292-307). The aggregate'sConfirmEmailtransition, and whatever it raises, runs only on a completing request (remarks:49).An already-confirmed account is still a success that writes nothing to the aggregate, but the token is spent first and the spend's result is returned, with
EmailConfirmedlogged only on a successful spend (:129-138). The comment above it (:124-128) is precise about which duplicate reaches this branch: a second, different token for an address already confirmed, or two concurrent redemptions of one link (redemption takes no lock, so both can pass the check). A sequential re-open of a link that already succeeded does not reach it: the first redemption spent the token, so the repeat is refused as an invalid token.[Rubric §11: Security]assesses whether a rejected request leaks account state or lets the wrong party act. Every token rejection, an invalid or expired token (:109-113), an account that no longer resolves (:118-122) and a token that fails the spend (:305-306), returns the identicalEmailConfirmationErrors.InvalidToken(HandlerName), differing only in a log reason string, and that rejection log carries no address and no account id (:324-327). The distinctPasswordRequiredanswer and the account-id log linesPasswordProofRequiredandPasswordNotChangeableare reachable only after the token checked out, so the id reveals nothing the caller did not prove (:222-224). The password proof shares the sign-in lockout, so a confirmation page is not a side door for password guessing.Walkthrough: the nested enum, two protected members, the handler method and five private steps.
AccountProof(:73-86): how the caller proved the account.UnitOfWork(:89): exposed for app-level extensions, same shape as the other Users bases.HandlerName(:95):protected virtual, defaulting toGetType().Name.HandleAsync(TCommand, CancellationToken)(:98-144): null-guard (:100); check the token viaValidateAsync(request.Email, request.Token, ...)(:106-108), failing generically on rejection (:109-113); load the resolved account through the write repository (:115-117), failing generically again if it is gone (:118-122); the already-confirmed branch (:129-138); otherwiseProveAccountAsyncand eitherCompleteAsyncorResult.Failure(proof.Errors)(:140-143).ProveAccountAsync(:195-229): no password credential (:200-203), then signed in as the account (:205-208), then a current password (:210-213), then a new password, accepted only whenTUserimplementsIPasswordChangeableUserand otherwise logged at Warning asPasswordNotChangeable(:215-225); anything else logsPasswordProofRequiredand fails withPasswordRequired(:227-228).VerifyCurrentPasswordAsync(:239-250): delegates toaccountClaims.VerifyCurrentPasswordAsync(authUser, request.Email, request.CurrentPassword!, ...)(:244-246), mapping success toAccountProof.CurrentPasswordand passing the lockout refusal orAuth.InvalidCredentialsthrough (:238,:247-249).CompleteAsync(:155-186): spend the token (:162-166);ClaimWithNewPasswordAsyncfor aNewPasswordproof,user.ConfirmEmail()otherwise (:168-170), returning a failure untouched (:171-174); save (:176); clear the failed-attempt counter for aCurrentPasswordorNewPasswordproof, as a sign-in does (:178-182); logEmailConfirmedWithProofand return (:184-185).ClaimWithNewPasswordAsync(:262-282):accountClaims.ClaimWithNewPasswordAsync(user.Id, (IPasswordChangeableUser)user, request.NewPassword!, ...)(:267-269), which revokes the sessions and removes the second factor with their own saves before the account changes (doc:252-256); on successuser.ConfirmEmail()(:275) and the Warning-levelAccountClaimedlog (:276-279,:315-316).SpendTokenAsync(:292-307): described above.
Why it's built this way: it is the confirmation half of the same email-verification vertical whose send side is
SendEmailConfirmationHandlerBase<TUser, TCommand>; the two are separate handlers, not one, because sending is anonymous and always returns success while confirming is the one call in the vertical that actually mutates the aggregate. Deciding the proof (ProveAccountAsync, which changes nothing but the lockout counter,:188-189) is kept apart from acting on it (CompleteAsync), so a refused request never spends the token and never runs the aggregate transition.Where it's used: subclassed by ADC, whose
ConfirmEmailHandlerpasses all five dependencies through (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailHandler.cs:25-31). TheIAccountClaimServiceit needs is registered asservices.TryAddScoped<IAccountClaimService, AccountClaimService>()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:96), which the handler's parameter doc attributes toAddEmailConfirmation(:58-62). Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/EmailConfirmationHandlerBaseTests.csand byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/EmailConfirmation/ConfirmEmailAccountProofTests.cs:38, which pins each proof and refusal, including that the verified event is never raised on a refusal (:317).Caveats: the request validator, not this handler, is the only place a malformed request shape can produce a 400. A
TUserthat holds a password but does not implementIPasswordChangeableUsercannot be claimed with a new password: the request falls through toPasswordRequiredwith a Warning log (:217-224), so such an app can confirm only by sign-in or current password.
TwoFactorAttemptKey
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.TwoFactor·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/TwoFactorAttemptKey.cs:15· Level 0 · class (internal, static)
What it is: a one-method static helper that builds the failed-attempt counter key for an account's second-factor code (
TwoFactorAttemptKey.cs:15,Forat:20-21).Depends on: the
UserIdentifierTypealias andCultureInfo(BCL). No first-party types, which is why it sits at Level 0.Concept introduced, a separate counter namespace per credential.
[Rubric §11, Security]assesses whether brute-force budgets are scoped to what they protect.For(userId)returnstwo-factor:{id}with the id formatted byCultureInfo.InvariantCulture(TwoFactorAttemptKey.cs:20-21), so the second-factor budget is a different counter from the password-login one thatILoginProtectionServicekeeps for the same account (ADR-029), and a culture-dependent id format cannot split one account across two keys.Walkthrough:
internal static string For(UserIdentifierType userId)is an expression-bodied interpolation (TwoFactorAttemptKey.cs:20-21). Nothing else.Why it's built this way: three handlers need the identical key and a typo in one would give that endpoint its own silent, unshared budget, so the format lives once.
Where it's used:
ConfirmTwoFactorEnrollmentHandlerBase<TCommand>,DisableTwoFactorHandlerBase<TCommand>andRegenerateRecoveryCodesHandlerBase<TCommand>, each passing it toCheckLockoutAsync,IncrementFailedAttemptsAsyncandResetFailedAttemptsAsync. The Begin handler does not use it.
UserDataExportSectionDefaults
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ExportUserData·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/IUserDataExportSection.cs:105· Level 0 · class (static)
What it is: a static holder for one string constant: the sentence a data subject reads when a section of their export could not be produced and the app supplied no reason of its own.
Depends on: nothing. It is a single
const string, which is why it is Level 0 even though the export pipeline around it is not.Concept introduced, the caller-safe failure message.
[Rubric §30, Compliance, Privacy and Data Governance]assesses whether privacy obligations are met in the product rather than in a policy document: a data-subject access request has a legal deadline, so a partially unavailable package that says so plainly is a better answer than a failed request (ADR-076).[Rubric §11, Security]assesses what leaves the trust boundary: this text reaches an end user, so it is deliberately generic and carries no exception message, stack trace, peer address, or connection string; the detail goes to the log instead, through the handler-localExportSectionUnavailablesource-generated log message onExportUserDataHandlerBase<TUser, TQuery>(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:233).[Rubric §13, Observability and Operability]: splitting the audience in two (generic sentence out, full exception in) is the pattern, not an oversight.Walkthrough: one member,
public const string UnavailableReason(IUserDataExportSection.cs:112-113), whose value is "This section could not be retrieved. The data is unchanged; the export can be requested again later." The XML doc records the intent (IUserDataExportSection.cs:107-111): the subject learns the section is incomplete and retryable, and learns nothing about the internal failure.constrather thanstatic readonlybecause the value is compile-time and callers use it in default-parameter position and in object initializers.Why it's built this way: two call sites need the identical wording, and having them share a constant is what keeps a degraded section indistinguishable whether the section itself reported unavailability or the handler caught an exception on its behalf.
Where it's used: as the fallback in
UserDataExportSectionResult.Unavailablewhen the caller passes no reason (IUserDataExportSection.cs:99), and directly inExportUserDataHandlerBase<TUser, TQuery>'s catch block when a section throws (ExportUserDataHandlerBase.cs:227).
ResolvedAccount
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.SignInLinks·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:386· Level 0 · record struct (private, readonly, nested)
What it is: the private result of the account-resolution step inside
RedeemSignInLinkHandlerBase<TUser, TCommand>: the account a redemption resolved, plus whether this redemption confirmed its address (RedeemSignInLinkHandlerBase.cs:383-386).Depends on: only the enclosing class's
TUsertype parameter andbool. No first-party types of its own, which is why it sits at Level 0.Concept introduced, carry the fact forward instead of re-deriving it. Whether the aggregate's confirm transition ran is known only while the account is being resolved: once the save is done, an account confirmed by this redemption and one that was already confirmed read the same. Returning the flag beside the account lets the handler pass it to the
OnEmailOwnershipProvedAsyncextension point, whose doc states the purpose: it lets an app announce the proof exactly once (:163-167).[Rubric §15, Best Practices & Code Quality]assesses whether shared behavior has one owner: the flag is set by the framework at the one place the transition runs, not inferred by each app.Walkthrough: a positional
readonly record structwith two members,User(the tracked or just-saved account) andConfirmedByThisRedemption(:350-353). It is built in three places:falsefor an existing account that is already confirmed or whose type does not track confirmation (:202-205),trueonceConfirmExistingAccountAsyncsucceeds (:207-210), and, for a newly provisioned account, whether it was unconfirmed beforeConfirmIfNeededran (:242-243,:254).Why it's built this way: private and nested because nothing outside the redeem workflow needs it; it travels inside
Result<ResolvedAccount>(:178) andHandleAsyncunpacks it at once, usingUserfor the session (:113,:118) and passing the flag toOnEmailOwnershipProvedAsync(:114).Where it's used: only inside
RedeemSignInLinkHandlerBase<TUser, TCommand>: returned by the privateResolveAccountAsync(:178) andProvisionAccountAsync(:223), consumed byHandleAsync(:107-114).
UserDataExportSectionResult
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ExportUserData·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/IUserDataExportSection.cs:47· Level 1 · record (sealed)
What it is: what one
IUserDataExportSectionhands back: either its payload, or the fact that the payload could not be produced plus a caller-safe reason.Depends on:
UserDataExportSectionDefaults(Level 0, for the fallback reason string). BCL only otherwise (object,ArgumentException). It is the application-layer twin of the wire DTOUserDataExportSectionDTOthat the handler copies it into.Concept introduced, "unavailable" as a first-class value rather than an exception.
[Rubric §29, Resilience, Reliability and Business Continuity]assesses how a system behaves when a dependency is down. In a fan-out over N contributors, an exception is the wrong currency: it either aborts the whole package or gets swallowed. Modelling the negative outcome as a value (Available = falseplus a reason) means the degraded case is visible in the document the data subject receives, and the caller cannot forget to handle it.[Rubric §2, Design Patterns]: the two named static factories are the only construction paths, so an instance is always in one of exactly two legal shapes, the same private-construction discipline value objects use elsewhere in this codebase.Walkthrough
- Four
initmembers:required string SectionName(IUserDataExportSection.cs:50),required bool Available(:53),object? Data(:60), andstring? UnavailableReason(:67). The tworequiredmembers are the ones a result is meaningless without; the two nullable ones are mutually exclusive in practice. Datais typedobject?on purpose (:55-59): every contributor publishes its own DTO shape and the export is serialized as one JSON document, so the payload type cannot be known here. Its doc marks it PII by design: never log it, never cache it.UnavailableReason(:62-66) is documented as reaching the data subject, so it must never carry internal exception detail.Complete(sectionName, data)(:73-83) guards withArgumentException.ThrowIfNullOrWhiteSpace(sectionName)(:75) and returnsAvailable = true. Note that anullpayload is legal here: a section that provably holds nothing for this user returns a complete result with an empty body, which is a truthful answer rather than an unknown one (IUserDataExportSection.cs:11-14).Unavailable(sectionName, reason = null)(:91-101) applies the same name guard (:93) and falls back toUserDataExportSectionDefaults.UnavailableReasonwhen the caller supplies none (:99).
- Four
Why it's built this way: a
sealed recordwithinitmembers gives structural equality and immutability for free, which matters because these instances flow straight into a document that must not be mutated after assembly (ADR-076).Where it's used: the return type of
IUserDataExportSection.ExportAsync(IUserDataExportSection.cs:38), consumed byExportUserDataHandlerBase<TUser, TQuery>'sRunSectionAsync, which copies its four fields into aUserDataExportSectionDTO(ExportUserDataHandlerBase.cs:205-211). Produced by every concrete section, for example Store'sSalesUserDataExportSectionreturningCompletewith an empty payload for an account with no linked customer (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ExportUserData/SalesUserDataExportSection.cs:45) and with the mapped payload otherwise (:56).
IRedeemSignInLinkCommand
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.SignInLinks·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/IRedeemSignInLinkCommand.cs:10· Level 1 · interface
What it is: the contract an app's redeem-sign-in-link command record satisfies so the shared handler and controller bases can work with it: the
RedeemSignInLinkRequestplus the caller's IP and user-agent (IRedeemSignInLinkCommand.cs:10-17).Depends on:
ICommandWithRequest<out TRequest>closed overRedeemSignInLinkRequest(:10). No externals.Concept introduced: the same reason the other Users command records stay app-side (see
GetUserPreferencesQuery): each app's record carries its own pipeline markers, ADC's for instance addsITransactional(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RedeemSignInLink/RedeemSignInLinkCommand.cs:19-23). An interface lets the framework name the members it needs without owning the record.[Rubric §9, API & Contract Design]: the two extra members are request metadata the controller captures from the HTTP connection, not values the client supplies.Walkthrough:
IpAddress(:13) andUserAgent(:16), bothstring?, recorded on the new refresh session.Requestis inherited fromICommandWithRequest<RedeemSignInLinkRequest>.Where it's used: the
TCommandconstraint ofRedeemSignInLinkHandlerBase<TUser, TCommand>(RedeemSignInLinkHandlerBase.cs:69), which passes both members toIAuthenticationService.SignInVerifiedEmailOwnerAsync(:117-119); theTRedeemCommandconstraint ofSignInLinkControllerBase<TSendCommand, TRedeemCommand>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:39), which fills them fromClientIpAddressandClientUserAgent(:51,:54,:121). Implemented by ADC'sRedeemSignInLinkCommand(cited above).
IUserDataExportSection
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ExportUserData·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/IUserDataExportSection.cs:20· Level 2 · interface
What it is: the contributor contract for a data-subject export. One implementation is one module (or one cross-service peer client) that holds personal data keyed by user and can hand it over on request.
Depends on:
UserDataExportSectionResult(Level 1, its return type) and theUserIdentifierTypealias. Nothing external beyondTaskandCancellationToken.Concept introduced, the accumulating-registration extension point.
[Rubric §5, Vertical Slice]assesses whether a feature's pieces cluster inside the boundary that owns them: the export document is assembled centrally, but what each module contributes is written and registered by that module, so adding personal data to a module means adding one section, not editing a central projection.[Rubric §7, Microservices Readiness]: a section may be backed by an in-process repository read or by a gRPC client to an extracted peer, and the export handler cannot tell the difference.[Rubric §30, Compliance, Privacy and Data Governance]: this is the mechanism by which "all personal data we hold about you" stays complete as modules are added, which is the obligation ADR-076 exists to discharge.[Rubric §29, Resilience]: sections are explicitly best-effort, and the contract says so in its own remarks (IUserDataExportSection.cs:8-14): a throwing section degrades toAvailable = falseand the export still succeeds, because one unreachable peer must never deny a data subject the rest of their data.Walkthrough: two members.
string SectionName { get; }(IUserDataExportSection.cs:27), the stable name the section is published under in the document ("Engagement", "Sales"). The doc calls it part of the contract rather than a label to reword, because it appears verbatim in the package a data subject reads.Task<UserDataExportSectionResult> ExportAsync(UserIdentifierType userId, CancellationToken cancellationToken = default)(IUserDataExportSection.cs:38-40). Its doc states the tolerance explicitly: throwing is permitted, and the handler degrades the section, but returningUserDataExportSectionResult.Unavailableis preferred where the reason is known (:34-37).- Registration is a separate one-liner:
AddUserDataExportSection<TSection>()doesTryAddScoped<TSection>()plusTryAddEnumerable(ServiceDescriptor.Scoped<IUserDataExportSection, TSection>())(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Extensibility.cs:38-44).TryAddEnumerableis the load-bearing call: registrations accumulate across modules while the same type registered twice is added once, and registration order becomes document order (DependencyInjection.Extensibility.cs:19-26). The lifetime is scoped, so a section runs inside the request's unit of work and may take scoped dependencies (DependencyInjection.Extensibility.cs:27-30).
Why it's built this way: the alternative, a central export handler that knows every module's data, would couple the Identity module to every other module and would break the moment one of them was extracted into its own service. Fan-out over an injected
IEnumerable<IUserDataExportSection>keeps that knowledge inside each module and turns extraction into a change of what the section calls, not of who contributes.Where it's used: injected as
IEnumerable<IUserDataExportSection>intoExportUserDataHandlerBase<TUser, TQuery>(ExportUserDataHandlerBase.cs:63). Implemented byEngagementUserDataExportSectionandNotificationUserDataExportSection, registered in that order (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:66-67), and by Store'sSalesUserDataExportSection(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ExportUserData/SalesUserDataExportSection.cs:22), registered by its Identity module (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/IdentityModule.cs:40). Two more implementations exist only as test doubles that pin the degradation contract,ThrowingSectionandCancellingSection(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/ExportUserDataHandlerBaseTests.cs:415and:404).Caveats / not-in-source: whether a given section's peer is reachable in a given environment is a deployment fact, not a source fact. The source settles only that an unreachable peer degrades one section.
BeginTwoFactorEnrollmentHandlerBase<TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.TwoFactor·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/BeginTwoFactorEnrollmentHandlerBase.cs:41· Level 4 · class (abstract)
What it is: the shared start-two-factor-enrollment workflow: load the account's two-factor state, refuse if already enabled, resolve the account's display name, mint a fresh TOTP secret, and start the enrollment in the store in protected form (
BeginTwoFactorEnrollmentHandlerBase.cs:41,:55-101).Depends on:
ITwoFactorService,ITwoFactorStore,ITwoFactorSecretProtectorand anILoggeras primary-constructor parameters (:41-45); implementsICommandHandler<in TCommand, TResult>closed overResult<TwoFactorSetupResponse>(:45).TCommandis constrained toIUserScopedRequest(:46), the narrowest of this family's command constraints: this workflow reads only the caller's id and carries no request payload. Its one audit line is a private source-generated[LoggerMessage]method,TwoFactorEnrollmentStarted(:115-116), which is why the class is declaredpartial(:41). Externals:Microsoft.Extensions.Logging.Concept introduced: a fresh secret on every call, never a reuse. An interrupted enrollment must not leave a secret live that somebody who saw the first QR code could still key an authenticator with, so
HandleAsynccallstwoFactorService.GenerateSecret()unconditionally rather than resuming a prior attempt (:86, comment at:83-85).[Rubric §11: Security]assesses secret-material handling. The account is checked for an already-enabled factor before a new secret is even generated (:68-74); the store never receives the plaintext secret, onlysecretProtector.Protect(secret)(:88-90); and the response carries the plaintext secret plus a provisioning URI built by the service, never anything the handler constructs itself (:98-100). The class remarks state the rule: only the account owner gets the plaintext key, once, in the response.Walkthrough: one virtual member, one method and one abstract hook.
HandlerName(:52):protected virtual, defaulting toGetType().Name, the same source-stamping pattern used by every other handler base in this family.HandleAsync(TCommand, CancellationToken)(:55-101): null-guards the command (:59); loads the two-factor state (:61), returningError.NotFoundwhen absent (:62-66); returns aConflict(Authentication.TwoFactorAlreadyEnabled) when already enabled (:68-74); resolves the account label through the one abstract hook (:76), failingNotFoundwhen it comes back blank (:77-81); generates the secret (:86); starts the enrollment in the store with the protected secret (:88-90), propagating its failure untouched (:91-94); logsTwoFactorEnrollmentStarted(:96); and returns the plaintext secret and provisioning URI (:98-100).ResolveAccountNameAsync(UserIdentifierType, CancellationToken)(:111-113):protected abstract. The one app-specific step, because each app'sUserexposes its authenticator label (normally the email) differently.
Why it's built this way: enrollment, confirmation, disablement and recovery-code regeneration are four small, independently-testable steps rather than one wide handler, so each app subclass only ever forwards the app-specific lookups its use case actually needs. Each step owns its log message as a private
[LoggerMessage]method, so the message text lives beside the only code that emits it. Protecting the secret in the base rather than in each app's store means no app store can persist it in plaintext by omission; the default protector is the data-protection one registered byAddTwoFactorAuthentication(seeDependencyInjection).Where it's used: covered by
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/TwoFactorHandlerBaseTests.csthrough a test subclass, and end to end with the real protector byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/TwoFactor/TwoFactorSecretProtectionEndToEndTests.cs.Caveats: the plaintext secret is returned to the caller in the response; it is up to the transport (HTTPS) and the client to keep it confidential in transit, nothing in this handler encrypts the response further.
ConfirmTwoFactorEnrollmentHandlerBase<TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.TwoFactor·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/ConfirmTwoFactorEnrollmentHandlerBase.cs:39· Level 4 · class (abstract)
What it is: the shared confirm-enrollment workflow: refuse an account whose factor is already active, verify the caller's first TOTP code against the pending secret under a failed-attempt budget, generate a batch of recovery codes, and persist the completed enrollment (
ConfirmTwoFactorEnrollmentHandlerBase.cs:39,:54-106).Depends on:
ITwoFactorService,ITwoFactorAuthenticator,ITwoFactorStore,ILoginProtectionServiceand anILogger(:39-44); implementsICommandHandler<in TCommand, TResult>overResult<TwoFactorRecoveryCodesResponse>(:44).TCommandis anIUserScopedCommand<out TRequest>carrying aTwoFactorCodeRequest(:45). Also usesTwoFactorErrorsandTwoFactorAttemptKey(:75), and logs through a private source-generated[LoggerMessage]method,TwoFactorEnabled(:108-109), hence thepartialdeclaration (:39).Concept introduced: the pending secret has to still be there to confirm against, and a wrong code costs budget. The handler reads the state the Begin step wrote and fails with
TwoFactorErrors.TwoFactorEnrollmentMissingwhen there is no secret, treating an empty or zero-length secret the same as a missing one (:60-65,TwoFactorSecret is not { Length: > 0 } secret), so a confirm call that races an unstarted enrollment cannot verify against a blank value. A secret that is still stored on an already-active account is refused with anAuthentication.TwoFactorAlreadyEnabledconflict (:67-73), because the secret stays stored after enrollment and a time-based code alone would otherwise mint a fresh recovery set (SECURITY M228, remarks at the type). The code is checked throughITwoFactorAuthenticator.VerifyEnrollmentCodeAsync, so its time step is accepted once (:82-84); a wrong code increments the per-account counter (:87), the lockout is checked before verifying (:76-80), and success resets the counter (:91), the same way a wrong current password counts in the change-password workflow (ADR-029).[Rubric §11: Security]assesses brute-force resistance on secondary credentials. A stolen-token holder cannot enumerate six-digit codes through this endpoint without hitting the exponential lockout.[Rubric §1: SOLID]assesses open/closed. Verification and persistence (CompleteEnrollmentAsync) are delegated to collaborators, so the handler itself contains no cryptographic logic.Walkthrough: one virtual member and one method.
HandlerName(:51).HandleAsync(TCommand, CancellationToken)(:54-106): null-guard (:58); load state and fail on a missing/empty secret (:60-65); refuse an already-enabled account (:67-73); derive the counter key (:75) and fail with the lockout errors if locked out (:76-80); verify the submitted code (:82-84), on failure increment the counter and returnTwoFactorErrors.TwoFactorInvalid(:85-89); reset the counter (:91); generate recovery codes (:93); complete the enrollment with their hashes (:95-101); logTwoFactorEnabled(:103); return the plaintext codes to the caller once, in the response (:105).
Why it's built this way: recovery codes are only ever returned at this one moment, on the response of the call that completes enrollment, because the store only ever persists their hashes (
:95-98, the failure path at:99-101); the plaintext never touches the database.Where it's used:
BeginTwoFactorEnrollmentHandlerBase<TCommand>and this type are used together byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/TwoFactorHandlerBaseTests.csthrough a shared test subclass.Caveats: a failed
VerifyCodedoes not clear the pending secret, so the caller can retry with a fresh code from the same authenticator entry without restarting enrollment.
DisableTwoFactorHandlerBase<TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.TwoFactor·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/DisableTwoFactorHandlerBase.cs:36· Level 4 · class (abstract)
What it is: the shared turn-off-two-factor workflow: check the per-account lockout, challenge the submitted code against the active factor, and disable it in the store only when the challenge succeeds (
DisableTwoFactorHandlerBase.cs:36,:50-93).Depends on:
ITwoFactorAuthenticator,ITwoFactorStore,ILoginProtectionServiceand anILogger(:36-40); implementsICommandHandler<in TCommand, TResult>overResult(:40).TCommandis anIUserScopedCommand<out TRequest>carrying aTwoFactorCodeRequest(:41). Also usesTwoFactorErrorsandTwoFactorAttemptKey(:54), and logs through a private source-generated[LoggerMessage]method,TwoFactorDisabled(:95-96), hence thepartialdeclaration (:36).Concept introduced: a distinguishable not-enrolled outcome, behind a lockout.
ChallengeAsyncreturns aTwoFactorOutcome, and the handler treatsNotEnrolledas a distinct failure (TwoFactorErrors.TwoFactorNotEnrolled,:77-80, comment at:74-76) rather than an idempotent success: the caller just presented a code, and the code was never actually checked against anything, so the response says so rather than silently agreeing. Ahead of the challenge the handler consults the lockout for the account's counter key (:54-59); a challenge failure whose error code isTwoFactorErrors.TwoFactorInvalidCodeincrements the counter (:64-70), and a good challenge resets it (:82). That is the M228 hardening: a wrong code counts against the same budget as a wrong current password in the change-password workflow (ADR-029).[Rubric §11: Security]assesses whether the disable path itself is gated. Disabling two-factor cannot happen without a live code challenge, and a stolen-token holder cannot guess codes here without hitting the lockout, so an attacker who only has the session cookie (and not the authenticator) cannot turn protection off.Walkthrough: one virtual member and one method.
HandlerName(:47).HandleAsync(TCommand, CancellationToken)(:50-93): null-guard (:52); derive the counter key and return the lockout failure when locked out (:54-59); challenge the code (:61-63), counting a wrong-code failure and returning the challenge errors (:64-72); theNotEnrolledoutcome fails distinctly (:77-80); reset the counter (:82);DisableAsync(:84), returning its failure unchanged (:85-88); logTwoFactorDisabled(:90); return success (:92).
Why it's built this way: the challenge/store split mirrors the enrollment pair:
ITwoFactorAuthenticatorowns the live code check,ITwoFactorStoreowns the persisted state, and this handler only sequences the two.Where it's used: covered by
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/TwoFactorHandlerBaseTests.cs.Caveats: disabling does not clear previously issued recovery codes from the store on its own; that is
ITwoFactorStore.DisableAsync's contract, not visible from this handler.
RegenerateRecoveryCodesHandlerBase<TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.TwoFactor·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/RegenerateRecoveryCodesHandlerBase.cs:36· Level 4 · class (abstract)
What it is: the shared regenerate-recovery-codes workflow: check the per-account lockout, challenge the submitted code, then replace the account's whole recovery-code set (
RegenerateRecoveryCodesHandlerBase.cs:36,:51-98).Depends on:
ITwoFactorAuthenticator,ITwoFactorService,ITwoFactorStore,ILoginProtectionServiceand anILogger(:36-41), the widest primary constructor of the four TwoFactor bases; implementsICommandHandler<in TCommand, TResult>overResult<TwoFactorRecoveryCodesResponse>(:41).TCommandis anIUserScopedCommand<out TRequest>carrying aTwoFactorCodeRequest(:42). UsesTwoFactorAttemptKey(:57) and logs through a private source-generated[LoggerMessage]method,TwoFactorRecoveryCodesRegenerated(:100-101), hence thepartialdeclaration (:36).Concept introduced: regeneration replaces, it does not append, and it is not a code oracle.
ReplaceRecoveryCodesAsynctakes the freshly generated hash set and is expected to overwrite whatever codes existed before (:87-89), so a code from a batch the caller regenerated away is no longer valid, closing off an old code that may have leaked. A wrong code counts against the per-account budget (:67-72, M228, ADR-029), so the endpoint is not an unthrottled code oracle for a stolen-token holder.[Rubric §11: Security]assesses whether the regenerate path is itself gated the same way disable is: the lockout check (:57-62) and a live code challenge, with the sameNotEnrolleddistinct failure, have to succeed first (:64-81).Walkthrough: one virtual member and one method.
HandlerName(:48).HandleAsync(TCommand, CancellationToken)(:51-98): null-guard (:55); derive the counter key and return the lockout failure when locked out (:57-62); challenge (:64-66), counting a wrong-code failure (:67-75); theNotEnrolledoutcome fails distinctly (:77-81); reset the counter (:83); generate a new code batch (:85); replace them in the store (:87-89), propagating a failure untouched (:90-93); logTwoFactorRecoveryCodesRegenerated(:95); return the new plaintext codes (:97).
Why it's built this way: it shares the challenge-then-store shape with
DisableTwoFactorHandlerBase<TCommand>and the generate-then-persist shape withConfirmTwoFactorEnrollmentHandlerBase<TCommand>, because regeneration is genuinely the union of the two operations.Where it's used: covered by
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/TwoFactorHandlerBaseTests.cs.Caveats: as with
ConfirmTwoFactorEnrollmentHandlerBase<TCommand>, the plaintext codes are returned exactly once, in this response; the store keeps only their hashes.
UserSessionExportDTO
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ExportUserData·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/RefreshSessionUserDataExportSection.cs:66· Level 5 · record (sealed)
What it is: one sign-in session as the data subject receives it in the export: when it was issued, when it expires or was revoked and why, and the client and device details recorded for it, with no token hash (
RefreshSessionUserDataExportSection.cs:47-52,:66-79).Depends on:
RefreshSession(the stored row it projects,:84) andPiiAttribute(applied as[property: Pii],:71-79).Concept: the export-side projection that keeps credentials material out of a portability document. It applies the
[Pii]marking taught in the primer (ADR-005) the same wayRefreshSessiondoes, so a log redactor masks the client and device members (:50-51).[Rubric §30, Compliance, Privacy and Data Governance]assesses whether personal data is identified and handled deliberately: every member here is either a timestamp, the revocation reason, or a[Pii]-marked client or device field, and the token hash and the successor's token hash are simply not members (:19-20).Walkthrough: a positional sealed record of thirteen members (
:66-79):CreatedAt,ExpiresAt, nullableRevokedAtandRevocationReason, then nine nullable[Pii]strings (IpAddress,UserAgent,DeviceId,DeviceName,DeviceModel,DeviceManufacturer,DevicePlatform,DeviceFormFactor,DeviceType). The one member is the static factoryFrom(RefreshSession)(:84-102), which null-guards its argument (:86) and copies the fields one for one, mapping the row'sReasonRevokedontoRevocationReason(:92).Why it's built this way: a dedicated export shape, rather than serializing the stored row, makes "never a secret" structural: a field added to
RefreshSessiondoes not reach the data subject until someone adds it here.Where it's used: produced only by
RefreshSessionUserDataExportSection(RefreshSessionUserDataExportSection.cs:43); pinned byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/ExportUserData/RefreshSessionUserDataExportSectionTests.cs.
RefreshSessionUserDataExportSection
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ExportUserData·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/RefreshSessionUserDataExportSection.cs:28· Level 7 · class (sealed)
What it is: the framework's own data-subject export section: the account's sign-in sessions, published as the
SignInSessionssection of the export document, so the access and portability export covers the session metadata the framework itself stores (RefreshSessionUserDataExportSection.cs:7-11,:28,:31).Depends on:
IRefreshSessionStore(primary-constructor parameter,:28),IUserDataExportSection(the contract it implements),UserDataExportSectionResultandUserSessionExportDTO.Concept: a contributor to the best-effort fan-out taught under
ExportUserDataHandlerBase<TUser, TQuery>, shipped by the framework rather than an app.[Rubric §30, Compliance, Privacy and Data Governance]: it exports every row, revoked and expired included, because a revoked row still carries the IP address, user agent and device fields captured at issue time, so leaving it out would export less than the store holds (:14-16); and it never exports a token hash (:19-20).Walkthrough:
Name(:31):public const string"SignInSessions", returned bySectionName(:34).ExportAsync(UserIdentifierType, CancellationToken)(:37-44): reads every session for the account throughIRefreshSessionStore.GetAllByUserAsync(:41; the store contract returns them oldest first,MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:58-59), projects each throughUserSessionExportDTO.From, and returnsUserDataExportSectionResult.Complete(:43). It does no error handling of its own: a store failure propagates and the handler'sRunSectionAsyncdegrades the section.
Why it's built this way: the refresh-session rows are framework data, so the framework contributes their export rather than asking every app to write the same section (ADR-076, ADR-097).
Where it's used: registered by
AddInfrastructurethroughAddUserDataExportSection<RefreshSessionUserDataExportSection>()right after the refresh-session store (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:199-202), so every host that issues sessions exports them with no app code; the comment notes it is inert on a host with no export handler, because nothing resolves the section there (:176-177). Tested byRefreshSessionUserDataExportSectionTestsand the registration check inMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/DependencyInjectionInfrastructureTests.cs.
ExportUserDataHandlerBase<TUser, TQuery>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ExportUserData·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:61· Level 8 · class (abstract partial, generic)
What it is: the shared data-subject export workflow (GDPR/CCPA access and portability). It authorizes the caller, loads the account read-only, asks the subclass for the app's own snapshot of that account, fans out best-effort over every registered
IUserDataExportSection, and assembles one JSON-ready package the data subject can be handed.Depends on:
IUnitOfWorkand, through it,IReadRepository<TEntity, TIdentifierType>;IUserDataExportSection(injected as anIEnumerable);IUserOwnedRequest(theTQueryconstraint) andUserOwnershipRule;AuditableAggregateRootEntity<TIdentifierType>(theTUserconstraint);IQueryHandler<in TQuery, TResult>(the contract it implements);Result/Error; the Shared-layer DTOsUserDataExportDTOandUserDataExportSectionDTO(MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:15and:61); andUserDataExportSectionDefaults.IAuditTrailWriteris injected through the primary constructor too (ExportUserDataHandlerBase.cs:64) and records each completed export (class remarks:33-39). Externals:TimeProviderandILogger(both injected through the primary constructor,ExportUserDataHandlerBase.cs:65-66), plus the[LoggerMessage]source generator fromMicrosoft.Extensions.Loggingfor its one private log method (:232-233).Concept introduced, the template-method handler that owns the workflow and delegates only what is genuinely app-specific.
[Rubric §2, Design Patterns]assesses deliberate pattern use: this is Template Method applied to a use case, with exactly three extension points (one abstract role check, one abstract projection, one virtual tail) and everything else fixed.[Rubric §15, Best Practices & Code Quality]: the workflow, the access record included, lives once in the base, leaving each subclass with the two decisions that actually differ (class remarksExportUserDataHandlerBase.cs:19-31).[Rubric §30, Compliance, Privacy and Data Governance]: the assembled document is PII by design, so its class doc states it must never be logged or cached, and notes that the caching query decorator is not applicable because the query implements noIQueryCacheable(ExportUserDataHandlerBase.cs:55-56); and every completed export leaves an access record on the audit trail that carries identifiers only, never the exported content (:33-39).[Rubric §29, Resilience]: the fan-out degrades per section rather than failing, since a data-subject request carries a legal deadline (ADR-076).[Rubric §14, Testability]: because authorization arrives inside the query and time arrives asTimeProvider, the whole workflow is exercised with mocks and no host (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/ExportUserDataHandlerBaseTests.cs:18).Walkthrough
- Shape and constraints (
ExportUserDataHandlerBase.cs:61-68): a primary-constructorabstract partialclass (partial so the logging source generator can supply the body of its private log method) takingIUnitOfWork,IEnumerable<IUserDataExportSection>,IAuditTrailWriter,TimeProvider, andILogger, implementingIQueryHandler<TQuery, Result<UserDataExportDTO>>, withTUser : AuditableAggregateRootEntity<UserIdentifierType>andTQuery : IUserOwnedRequest. CurrentFormatVersion = "1.0"(:74) is stamped into the envelope. Its doc is precise about scope (:70-73): it versions the envelope only, so an app changing its own subject or section payloads does not move it.ExportedAuditOperation = "Exported"(:80) is the operation name written to the audit trail for every completed export, against the exported account's type and id with the caller as the actor (:76-79).UnitOfWorkis exposedprotected(:83) purely so a subject-snapshot override can read further aggregates.HandlerNameisvirtualand defaults toGetType().Name(:90), so an app subclass namedExportUserDataHandlerreports that name in the error payload (:85-89).HandleAsync(:93-149). It null-guards the query (:97), then runs the ownership gate throughUserOwnershipRule.CheckOwnershipwithHasExportPrivilege(query.CurrentUserRole)and the code"User.ExportForbidden"(:100-109), failing fast on rejection.- The read (
:111-117):unitOfWork.GetReadRepository<TUser, UserIdentifierType>()thenGetByIdAsync. The class doc gives the reason (:48-52): this is a query handler, it never calls the unit of work'sSaveChangesAsync, and a no-tracking read is the correct choice for a projection that is only read. A missing account returnsError.NotFound.WithSource(HandlerName).WithTarget(typeof(TUser).Name)(:115-116). - The subject snapshot (
:119): oneawaiton the abstractBuildSubjectSnapshotAsync. - The fan-out (
:121-127): a plainforeachover the injected sections, awaited one at a time. The comment states both reasons (:121-122): sections share the scoped unit of work and itsDbContext, which is not thread-safe, and registration order is the published order of the document. This is the one place where the obvious "parallelize the I/O" instinct is wrong. - The envelope (
:129-136):FormatVersion,GeneratedOn = timeProvider.GetUtcNow(),UserId, the subject, and the section envelopes. - The access record (
:138-144):auditTrailWriter.RecordAsyncwith the account type's full name, the account id formatted invariantly,ExportedAuditOperation, andquery.CurrentUserIdas the actor, so an export of someone else's account reads as such. It runs before the package is handed back, and a failure to write it fails the export: the class remarks state that personal data is not released without its access record, that the write is inert in a host whose trail is off, and that a refused or not-found request records nothing (:33-39). The trail writer's save is its own, of its own row, so the handler still never saves through the unit of work (:49-50). - The tail (
:146):OnExportCompletedAsync, thenResult.Success(export)(:148). RunSectionAsync(:194-230) is the degradation boundary. It calls the section, copies the four result fields into aUserDataExportSectionDTO(:205-211), and catches with the filterwhen (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)(:213), so only the caller's cancellation is not degradation: anOperationCanceledExceptionwhile the caller's token is cancelled propagates as cancellation. A section's own timeout (anHttpClient.Timeout, or a linked token, surfacing as anOperationCanceledExceptionwhile the caller's token is still live) is a contributor failure like any other and degrades just that section (comment:215-218). On any caught exception it logs the full exception through its own private source-generatedExportSectionUnavailable(:221, declared at:232-233atLogLevel.Warningwith the template "Data-subject export section {Section} unavailable for user {UserId}; export continues with Available=false") and returns an envelope withAvailable = falseand the genericUserDataExportSectionDefaults.UnavailableReason(:223-228): detail to the log, nothing internal to the subject.- The three extension points:
HasExportPrivilege(string?)(abstract,:157), the role that bypasses ownership;BuildSubjectSnapshotAsync(TUser, TQuery, CancellationToken)(abstract,:171-174), which fields of the account are portable personal data, asynchronous and given the query because an app may need to read a second owned aggregate (:24-27); andOnExportCompletedAsync(...)(virtual, defaulting toTask.CompletedTask,:187-192), the app's tail for extras such as a metric or a notification, run after the access record is written, documented as not mutating the export and as owning its own failures because the export has already succeeded (:176-181).
- Shape and constraints (
Why it's built this way: ADR-076 records the decision, and the shape deliberately mirrors
DeleteUserHandlerBase<TUser, TCommand>: the same ownership gate through the same helper, the same privileged-role hook. The credential fields are excluded from the snapshot by contract (:159-163): a password hash and salt and an external-provider key are secrets, not portable personal data. Refresh-token material is not the subject snapshot's concern at all: sign-in sessions reach the export through the framework's ownRefreshSessionUserDataExportSection, which projects every session without its token hash. The degraded-section log isWarning, notError, on purpose: a degraded section is an expected, handled outcome of a best-effort fan-out and the request itself still succeeds (:232). Declaring that log method on the class itself keeps it next to the only call site, while the log category is whateverILoggerthe app subclass passes to the primary constructor.Where it's used: subclassed in each app's Identity Application assembly, where the convention scanner picks the concrete subclass up as an ordinary
IQueryHandlerwith no extra registration (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:80, and the point is spelled out in the export-section registration doc atMMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Extensibility.cs:31-36). ADC'sExportUserDataHandlercloses it overUserandExportUserDataQueryand overrides only the two abstract members (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:33, privilege =UserRole.IsOrganizerat:42, snapshot at:45), passing the base all five constructor arguments,IAuditTrailWriterincluded (ExportUserDataHandler.cs:36,:39). Store's does the same with its ownUser(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:40, base call at:46). Behaviour is pinned byExportUserDataHandlerBaseTests, including a section that throws (.../ExportUserDataHandlerBaseTests.cs:139), the caller cancelling during a section, which propagates (:218), a section timing out on its own while the caller's token is live, which degrades only that section (:236), the access record written with the caller as actor (:254), and an export that fails when the record cannot be written (:316).Caveats / not-in-source: the framework also ships an abstract
[FeatureGate]-d endpoint,DataExportControllerBase<TQuery>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:60-61), but neither app subclasses it: both kept their own export endpoints on top of this handler base, which the ADR records as an unadopted part of the decision.
RedeemSignInLinkHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.SignInLinks·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:62· Level 8 · class (abstract, partial)
What it is: the shared redeem-a-sign-in-link workflow (ADR-116). It spends the single-use token, resolves the account behind the address (creating it when an invitation allows), marks the address confirmed, and opens a session through
IAuthenticationService(RedeemSignInLinkHandlerBase.cs:18-22,:62-387).Depends on: five primary-constructor parameters (
:62-67):IUnitOfWork,ISignInLinkTokenService,IAuthenticationService,IOptions<SignInLinkSettings>and a plainILogger. ImplementsICommandHandler<in TCommand, TResult>closed overTCommandandResult<AuthenticationResponse>(:67). Constraints:TUseris anAuditableAggregateRootEntity<TIdentifierType>overUserIdentifierTypethat is also anIEmailIdentifiedUser(:68), which is what lets the workflow find the account by address itself throughUserEmailLookup(typeparam doc:52-55), andTCommandis anIRedeemSignInLinkCommand(:69). Also usesEmail,SignInLinkGrant,SignInLinkProfile,SignInLinkErrors,ErrorandAuthErrorCodes(the concurrent-insert conflict),IEmailConfirmableUser,IAuthUser,PasswordCredentialandIPasswordClearableUser. Externals:Microsoft.Extensions.OptionsandMicrosoft.Extensions.Logging(source-generated[LoggerMessage],:366-381).Concept introduced: spend the proof before you look anything up. The token is validated and consumed (
:100-106) before the account is resolved (:108), so a caller with no valid token learns nothing about whether an address holds an account; every rejection up to and including the spend collapses to one invalid-link error throughRejected(:360-364, class remarks:25-28).[Rubric §11: Security]assesses account-enumeration and credential-handling exposure. Beyond the token-first order, the audit lines carry no address (:379-381), and an unconfirmed account that holds password material has its refresh sessions revoked and its password removed when a link confirms it, because the link proves the mailbox, not the password set on that account (:300-335, remarks:42-49).[Rubric §15: Best Practices & Code Quality]assesses whether shared behavior has one owner. The app supplies only the optional extension points (the address lookup is the framework's own); the order of spend, resolve, confirm and sign-in lives once here.Walkthrough: three protected members, three extension points, one public method.
UnitOfWork(:72),Settings(:75) andHandlerName(:81, theGetType().Namedefault reported as the errorsource).HandleAsync(TCommand, CancellationToken)(:84-128): null-guards the command; rejects whenSettings.Enabledis false (:90-93) or the address is malformed (:95-98); callsValidateAndConsumeAsyncand rejects a refused token (:100-106); resolves the account (:108-112); runsOnEmailOwnershipProvedAsyncwith the resolved account'sConfirmedByThisRedemptionflag (:114-116); then opens the session withSignInVerifiedEmailOwnerAsync(user.Id, command.IpAddress, command.UserAgent, ...)(:118-120) and logs the purpose on success (:122-125).ProvisionUser(:144-145, virtual): default returns the invalid-link failure, so account creation through a link is opt-in per app (remarks:31-34).OnUserProvisionedAsync(:154-155) andOnEmailOwnershipProvedAsync(TUser, SignInLinkGrant, bool confirmedByThisRedemption, CancellationToken)(:172-177): virtual no-op post-save extension points. The flag istrueonly when this redemption moved anIEmailConfirmableUserfrom unconfirmed to confirmed, so an app can announce the proof exactly once (:164-169).ResolveAccountAsync(:179-212, private): looks the address up untracked through the read repository'sFindUntrackedByEmailAsync(:186-189) and hands a miss toProvisionAccountAsync(:191-194); with an account, reloads it tracked throughGetRepository(:185,:196), refuses if it is no longer resolvable (:197-201), returns it unconfirmed-by-this-redemption when it is already confirmed or not confirmable (:203-206), and otherwise confirms it throughConfirmExistingAccountAsync(:208-211).ProvisionAccountAsync(:224-282, private): refuses unless the grant carries a profile (:231-235); callsProvisionUserand returns its failure as is (:237-241); records whether the new account was unconfirmed and confirms it (:243-248); adds the account (:250) and saves inside atry(:252-276), then callsOnUserProvisionedAsync(:278) and logsAccountProvisioned(:280). The lookup inResolveAccountAsyncis a check-then-act, so two redemptions of one invitation (a double tap, a retry), or an invitation racing a registration, can both find no account, and the loser fails only at the save on the unique email index (comment:260-265). The catch is a generalcatch (Exception)under aCA1031suppression, because the persistence exception type is not visible from the Application layer (:256-258). It re-checks the address throughAddressNowHasAccountAsync(:284-288, an untrackedFindUntrackedByEmailAsyncwithCancellationToken.None, so a cancelled save can still be classified) and, when an account now exists, logs the rejection and returnsError.Conflict(AuthErrorCodes.EmailAlreadyExists, ...)(:266-273); anything else rethrows (:275). It returns the conflict rather than continuing on this unit of work, because the failed insert stays tracked and the session save that follows would re-issue it (:263-265).ConfirmExistingAccountAsync(:300-335, private): an account with no stored password is just confirmed and saved (:302-305); a password account whose type is notIPasswordClearableUseris refused before any mutation (:308-312); otherwise sessions are revoked first (:316-320), thenClearPassword(:322-326) and the confirming save (:328).ConfirmAndSaveAsync(:341-351),IsUnconfirmed(:353) andConfirmIfNeeded(:355-358): confirm then save, the unconfirmed test, or a no-op success for a type that is not confirmable.
Why it's built this way: the redeem path is the one that turns a mailbox proof into a session, so the ordering decisions (spend first, revoke before mutate, refuse before mutate) are the part worth not re-deriving per app; the comments at
:307and:314-315state why each step precedes the next. The concurrent-insert recovery is the same one registration uses (comment:262), so a lost race answers with the email conflict instead of an unhandled persistence error. Sign-in links are part of the opt-in identity completions (ADR-116), and theEnabledgate keeps a host that has not turned them on answering the generic refusal.Where it's used: subclassed by ADC's
RedeemSignInLinkHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RedeemSignInLink/RedeemSignInLinkHandler.cs:46), which passes the base its five constructor arguments (:54-55) and overrides the three extension points:ProvisionUser(:66),OnUserProvisionedAsync(:92) and the four-parameterOnEmailOwnershipProvedAsyncwith the confirmation flag (:107-108); the address lookup is the base's own. Consumed through the closedICommandHandler<TRedeemCommand, Result<AuthenticationResponse>>bySignInLinkControllerBase<TSendCommand, TRedeemCommand>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:37,:45). Pinned byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/SignInLinkHandlerBaseTests.cs:34, including an invitation whose insert loses a race and returns the email conflict (:362), and through test subclasses such asPasswordAccountRedeemHandler<TUser>(:809-817).Caveats: the token is spent before the account is resolved, so a redemption that fails later (no account and no invitation profile, a refused password account, an invitation that loses the concurrent-insert race) still consumes the link; the caller requests a new one, or signs in to the account that now exists. An app that overrides
ProvisionUserreturns an unsaved account: the workflow adds and saves it (:250,:252-276).
SendSignInLinkHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.SignInLinks·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:62· Level 8 · class (abstract, partial)
What it is: the shared email-me-a-sign-in-link workflow (ADR-116): resolve the account behind the address, mint a short-lived single-use token, and email the link. The handler runs twice per request: the inline dispatch only schedules the command as an internal command (ADR-114) and answers
Result.Success(), and the scheduled execution does the work (SendSignInLinkHandlerBase.cs:19-24,:58-217).Depends on: six primary-constructor parameters (
:59-64):IUnitOfWork,ISignInLinkTokenService,IEmailSender,IInternalCommandScheduler,IOptions<SignInLinkSettings>and a plainILogger. ImplementsICommandHandler<in TCommand, TResult>closed overTCommandandResult(:64). Constraints:TUseris anAuditableAggregateRootEntity<TIdentifierType>overUserIdentifierType(:65);TCommandis anICommandWithRequest<out TRequest>closed overSendSignInLinkRequestAND anIInternalCommand(:66), because the inline dispatch schedules it; the typeparam doc asks the app to give the record anInternalCommandNameAttribute(:48-51). ReadsInternalCommandExecution.IsActiveto tell the two runs apart (:85). Also usesEmail,SignInLinkPurposeandUserEmailResources. Externals:Microsoft.Extensions.Options,Microsoft.Extensions.Logging([LoggerMessage],:204-216) andSystem.Net.WebUtility.Concept introduced: success-always as anti-enumeration, with the work moved off the request. The inline dispatch never looks the address up: with the feature enabled it writes one queue row and answers success, and with it disabled it answers success and schedules nothing (class remarks
:25-30, the same ruleForgotPasswordHandlerBasefollows). The one failure it can return is a failure to write the row, which does not depend on the address (:94-98).[Rubric §11: Security]assesses account-enumeration exposure. Because the lookup, the token and the send all happen in the scheduled execution, neither the answer nor its timing carries a signal about which addresses hold accounts. On that path a malformed address (:107-111), an address with no account (:114-119) and a throttled token request (:124-128) complete the row without an email; the no-account extension point runs insideNotifyNoAccountAsync(:192-202), which swallows and logs anything it throws other than a cancellation; and the audit lines carry no address (:210,:214). The token is issued on the scheduled path because nothing needs it before the response and a queue row must not carry the raw credential (:36-37).[Rubric §29: Resilience and Business Continuity]assesses whether a failed side effect is retried and surfaced. A failed send is not swallowed: it propagates, so the internal-command processor logs it with the stack, retries the row with backoff and dead-letters it visibly if it never clears (:133-138, remarks:35-36).[Rubric §27: i18n]assesses whether user-facing text follows the user's culture. Subject and body are composed insideUserEmailResources.InRecipientCulture(user, ...)(:135-137), so the email reads in the account's stored culture rather than the request's.Walkthrough: two protected members, four extension points, one public method and two private paths.
UnitOfWork(:69, exposed so the lookup override can reach a read repository) andSettings(:72).HandleAsync(TCommand, CancellationToken)(:75-88): null-guards; answers success whenSettings.Enabledis false orSignInUrlis blank (:79-83); then branches onInternalCommandExecution.IsActivetoSendAsync(the scheduled execution) orScheduleAsync(the inline dispatch) (:85-87).ScheduleAsync(:91-101, private):scheduler.ScheduleAsync(command, ...); on failure logsSignInLinkScheduleFailedatErrorand returns the scheduler's errors (:94-98).SendAsync(:104-142, private): parses the address (:106); looks the account up untracked (:113), callingNotifyNoAccountAsyncwhen there is none (:117); issues a token withSignInLinkPurpose.SignInand no profile (:121-123); composes the link withSettings.ComposeLink(:131); sends the localized HTML email (:135-138); and logs the request (:140).FindUntrackedByEmailAsync(:151, abstract): the app's own no-tracking lookup.OnNoAccountAsync(:167, virtual no-op): lets an app re-issue a pending invitation for an address that holds none (remarks:40-44).ComposeSubject(:174) andComposeBody(string)(:179-189): virtual, resource-backed; the body HTML-encodes the link (:186) and states the lifetime fromSignInLifetimeMinutes(:183,:187).NotifyNoAccountAsync(:192-202, private): the exception-swallowing wrapper above.
Why it's built this way: this path never creates an account. Creating one is what an invitation does, and the app issues an invitation with
SignInLinkPurpose.InvitethroughISignInLinkTokenServicedirectly (remarks:39-44). Scheduling the work as an internal command gives the send durability and retries without a caller to leak the outcome to: the comment at:133-134states that there is no caller on the scheduled path, so a send failure can propagate.Where it's used: subclassed by ADC's
SendSignInLinkHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkHandler.cs:44), which takes the scheduler as a constructor parameter (:50) and overridesFindUntrackedByEmailAsync(:60) andOnNoAccountAsync(:72). Consumed through the closedICommandHandler<TSendCommand, Result>bySignInLinkControllerBase<TSendCommand, TRedeemCommand>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:36,:38,:42), and again by the internal-command processor when the scheduled row is drained. Pinned byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/SignInLinkHandlerBaseTests.cs:34throughTestSendSignInLinkHandler(:795) andNoAccountSendSignInLinkHandler(:831).Caveats: unlike the redeem base it declares no
HandlerName. Because the inline answer is success for every address, the HTTP response cannot be used to diagnose a missing email; read theSign-in link request not actioned ({Reason})audit line (:211-212) and, for a failed send, the internal command's retry and dead-letter record instead. A host that does not drain internal commands accepts the request and never sends the email.
InProcessLockHandle
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Concurrency·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/InProcessDistributedLock.cs:79· Level 0 · class (private nested, sealed)
What it is: the disposable release token that
InProcessDistributedLockhands back on a successful acquire. Disposing it removes exactly the key that acquisition added, exactly once.Depends on: nothing first-party. BCL only: the owner's
ConcurrentDictionary<string, byte>and the key are passed into its primary constructor;Interlockedprovides the once-only latch,IAsyncDisposable/ValueTaskthe shape.Concept introduced, the acquisition handle as a scope token.
[Rubric §2, Design Patterns]assesses whether recurring problems use recognised patterns deliberately; returning a disposable instead of exposing aRelease(key)method is the scope-bound-resource shape theIDistributedLockcontract mandates, and it is what letsawait usingrelease the lock even when the guarded work throws. The token is also what makes release owner-scoped: the handle closes over the key it added, so it cannot free anybody else's acquisition.Walkthrough: the primary constructor takes the owner's
helddictionary and thekey(InProcessDistributedLock.cs:79); a singleint _releasedfield (InProcessDistributedLock.cs:81) is the latch.DisposeAsync(InProcessDistributedLock.cs:83-91) runsInterlocked.Exchange(ref _released, 1) == 0and only then callsheld.TryRemove(key, out _)(InProcessDistributedLock.cs:85-88), so a second disposal is a no-op and the contract's "disposal is idempotent" clause holds. It returnsValueTask.CompletedTask(InProcessDistributedLock.cs:90) because removing a key from aConcurrentDictionaryis synchronous, so there is no state machine to allocate.Why it's built this way: an interlocked latch rather than a plain bool because a handle can be disposed from more than one thread (an
await usingunwind plus an explicit dispose), and the removal has to happen exactly once, or a late second dispose would evict a key a different caller has since acquired.Where it's used: constructed by
InProcessDistributedLock.TryAcquireAsync(InProcessDistributedLock.cs:63) and returned as the contract'sIAsyncDisposable?; the APIIdempotencyFilteris the caller that disposes it.
RedisLockHandle
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Concurrency·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/RedisDistributedLock.cs:91· Level 0 · class (private nested, sealed)
What it is: the release token for a
RedisDistributedLockacquisition. Disposing it runs a compare-and-delete Lua script that removes the Redis key only while it still carries this acquisition's token.Depends on: nothing first-party. Externals: StackExchange.Redis (
IDatabase,RedisKey,RedisValue,RedisResult) andMicrosoft.Extensions.Logging;Interlockedfor the latch. Same handle shape asInProcessLockHandle, with real asynchronous work in the release.Concept: the owner-token release, the half of the
SET NX PXlock that keeps it honest (the acquire half is taught underRedisDistributedLock).[Rubric §13, Observability & Operability]assesses whether a system reports its own degradation: a release that finds nothing to delete is exactly the case where the guarded section outran its time-to-live and stopped being exclusive, so the handle logs a warning naming the key rather than swallowing it. The same applies when the release itself fails: it is best-effort by theIDistributedLockcontract, so the fault is logged as a warning and the holder's already-completed work is not turned into a failure.Walkthrough: the primary constructor captures the
IDatabase, the already-qualifiedRedisKey, this acquisition'sRedisValuetoken, and a logger (RedisDistributedLock.cs:91-95), with the sameint _releasedlatch (RedisDistributedLock.cs:97).DisposeAsync(RedisDistributedLock.cs:99-130) returns immediately when the latch was already set (RedisDistributedLock.cs:101-104); otherwise it evaluatesReleaseScriptwith that key and token inside atry(RedisDistributedLock.cs:111-115). The script isif redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end(RedisDistributedLock.cs:36-37), one round trip that compares and deletes atomically on the server. A0result means the key was already gone or is owned by someone else now, so there is nothing to release andLogLockAlreadyExpiredwarns (RedisDistributedLock.cs:117-122, message text atRedisDistributedLock.cs:84). Any exception from the release (a Redis fault or timeout) is caught by a deliberate broadcatch (Exception)under a justifiedCA1031suppression (RedisDistributedLock.cs:124-129) and logged throughLogLockReleaseFailed(RedisDistributedLock.cs:87-88) instead of propagating, because the release runs after the guarded work has already committed and the lock expires on its own time-to-live (RedisDistributedLock.cs:106-110). The code comment notesRedisTimeoutExceptionis not aRedisException, hence the broad catch.Why it's built this way: a plain
DELwould let a caller whose lock had already expired free the next holder's lock, which is precisely the double execution the lock exists to prevent (RedisDistributedLock.cs:32-34). Doing the comparison inside a Lua script makes compare-and-delete atomic server-side instead of a racy get-then-delete from the client (ADR-017).Where it's used: constructed by
RedisDistributedLock.TryAcquireAsync(RedisDistributedLock.cs:72).RedisDistributedLockTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Concurrency/RedisDistributedLockTests.cs:15) asserts the acquire/release pairing against a mockedIDatabase, including the qualified key the handle deletes.
AssemblyReference
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/AssemblyReference.cs:5· Level 0 · class (static)
What it is: a tiny static class that exposes the assembly it lives in plus that assembly's simple name. It is the Infrastructure layer's assembly-marker anchor, a deliberate, business-free type whose only job is to name "this assembly" for convention-based scanning.
Depends on:
System.Reflection.Assembly(BCL) only (AssemblyReference.cs:1). No first-party dependencies, which is why it sits at Level 0.Concept introduced, assembly-marker types for convention scanning.
[Rubric §2, Design Patterns]assesses whether recurring problems use recognised patterns; when a registration or test needs "every type in this assembly", handing the scanner a purpose-built anchor (typeof(AssemblyReference).Assembly) is the idiomatic form, far more stable thantypeof(SomeRandomHandler).Assemblypointing at a real class that might move or be renamed.[Rubric §1, SOLID](DIP): registration code depends on a stable, meaningless token rather than a concrete business type, so refactoring real Infrastructure types never breaks a scan. The same shape (AssemblyReference+ClassReference) repeats in every layer package (Application, Domain, API, and here in Infrastructure) so each assembly is self-describing without any cross-layer reference.Walkthrough: two
public static readonlyfields resolved once at type initialization (AssemblyReference.cs:7-8):Assemblyviatypeof(AssemblyReference).Assembly(AssemblyReference.cs:7), andAssemblyNameviaAssembly.GetName().Namewith a?? string.Emptyfallback (AssemblyReference.cs:8) so the field is never null even when the runtime reports no simple name.Why it's built this way: a purpose-built anchor decouples scanning from any business type, and repeating the identical shape in every package keeps each assembly self-describing without cross-layer references.
Where it's used: the Scrutor entity-configuration scan inside
DependencyInjection.AddInfrastructureusesFromAssemblyOf<ClassReference>()(the non-static companion, below); the architecture maps pin this assembly through the same anchor.
ClassReference
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/AssemblyReference.cs:11· Level 0 · class
What it is: the non-static companion to
AssemblyReferencein the Infrastructure layer, an empty, instantiable class used wherever a generic type parameter needs an assembly anchor and a static class will not satisfy the constraint.Depends on: nothing first-party; nothing from the BCL beyond
object.Concept: the companion half of the marker pattern taught under
AssemblyReference. C# static classes cannot be used as generic type arguments, so any registration helper constrained to an instantiable reference type (for example Scrutor'sFromAssemblyOf<T>()) is handedClassReferenceinstead ofAssemblyReference.[Rubric §33, Developer Experience]assesses how conventional the inner loop is: one token stands in for "this assembly" everywhere, so a developer wiring a new scan never has to hunt for a suitable real type.Walkthrough: a single-line body-less type declaration at
AssemblyReference.cs:11(public class ClassReference;). No members.Where it's used:
DependencyInjection.AddInfrastructurecallsservices.Scan(scan => scan.FromAssemblyOf<ClassReference>()...)(DependencyInjection.cs:135-139, the anchor itself at:112) to discover everyIEntityTypeConfigurationBase<TEntity, TIdentifierType>in the Infrastructure assembly and register it as its implemented interfaces with a scoped lifetime.
UseDatabaseAttribute
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/UseDatabaseAttribute.cs:22· Level 0 · class (sealed attribute)
What it is: a declarative attribute placed on an entity type configuration class to name the logical data source (database) that entity targets. It is the "which database" half of the database-per-microservice routing story; the sibling
UseDataSourceAttributeis the "which engine" half.Depends on:
System.Attribute(BCL) only. Its resolved logical name is consumed downstream by the data-source machinery (DataSourceResolver,EntityDataSourceRegistry) and mapped to a connection string through theDataSourcesconfiguration entries modelled byDataSourceEntrySettings/DataSourcesSettings.Concept introduced, declarative database-per-service routing.
[Rubric §8, Data Architecture]assesses how the model maps to physical stores;[Rubric §7, Microservices Readiness]assesses whether a module can be lifted out with its own database (ADR-006). The attribute's XML doc (UseDatabaseAttribute.cs:8-18) spells out the three-step resolution order for an entity's logical name: (1) this attribute on the concrete configuration class (inherited); (2) the module name derived from the entity namespace, the segment beforeDomain; (3) the literal"Default", the top-levelConnectionStringssection. A logical name with noDataSourcesentry (or whose connection string equals the top-level one) collapses onto theDefaultphysical source (UseDatabaseAttribute.cs:15-17), so a host that configures nothing behaves exactly like a single-database monolith. This "convention with an explicit override" shape is the load-bearing idea: most modules never apply the attribute and ride the namespace convention.Walkthrough:
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)](UseDatabaseAttribute.cs:21).Inherited = trueis deliberate: annotating a per-module configuration base class propagates the database assignment to every derived configuration, so a module can pin all its entities to one database in a single place.AllowMultiple = falseforbids an ambiguous second assignment.- Primary-constructor parameter
name(UseDatabaseAttribute.cs:22), the logical name (for example"Conference", the example the doc itself uses at:20). Nameget-only property (UseDatabaseAttribute.cs:25) initialized from that parameter, the value the resolver reads.
Why it's built this way: an attribute keeps the database choice declarative and co-located with the entity configuration rather than buried in a registration method, and
Inherited = trueturns per-module assignment into one annotation instead of one per entity (ADR-006, database per microservice).Where it's used: applied on concrete EF entity type configuration classes in the modules; read up front by the eager
EntityDataSourceRegistryso routing does not depend on a model having been built.
DecorationKey
MMCA.Common.Application, MMCA.Common.Infrastructure, MMCA.Common.UI (linked source) ·
MMCA.Common.DependencyInjection·MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:303· Level 0 · record (private, sealed, nested)
What it is: the service key under which a decorated registration's original is parked. It is a private record nested inside
ServiceCollectionDecoration(ServiceCollectionDecoration.cs:303-308), carrying the decorated closed service type for diagnostics only (:302).Depends on: BCL only (
Type,RuntimeHelpers).Concept: identity, not value, as the key. A record normally compares by value, so two keys for the same service type would be equal. This one overrides
Equals(DecorationKey?)withReferenceEquals(:305) andGetHashCodewithRuntimeHelpers.GetHashCode(this)(:307), so every decoration mints a key that only it holds. The doc states why (:298-301): when a service is decorated twice, each decorator's factory reaches exactly the registration it wrapped, never the other decorator's original. The keyed-service mechanics are taught underServiceCollectionDecoration.Walkthrough: one positional member,
Type ServiceType(:303), plus the two identity overrides (:305,:307).Where it's used: created once per matched registration in
DecorateEach(ServiceCollectionDecoration.cs:197), passed toAsKeyedto register the original under it (:200,:227-241), and resolved throughGetRequiredKeyedServiceby the replacement factory (:203). Nothing outside the file can name it.
ScanRegistration
MMCA.Common.Application, MMCA.Common.Infrastructure, MMCA.Common.UI (linked source) ·
MMCA.Common.DependencyInjection·MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:8· Level 0 · enum (internal)
What it is: the two shapes in which an assembly scan registers each class it finds (
ServiceCollectionDecoration.cs:7-18).Depends on: nothing.
Concept: covered under
ServiceCollectionDecoration, whoseAddAssignableTypestakes it as a parameter.Walkthrough: two members.
ImplementedInterfaces(:11): one registration per implemented interface, each mapping to the class (:10). Each interface resolution activates its own instance.SelfWithInterfaces(:17): the class registered as itself, plus one registration per interface that forwards to that self registration, so every interface resolves the same instance within its lifetime (:13-16). An open generic class gets only its self registration in this mode, because a forwarding factory cannot be open (ServiceCollectionDecoration.cs:84-86).
Where it's used:
ScanModuleApplicationServicespicksImplementedInterfaces(singleton) for domain and integration event handlers and (scoped) for command and query handlers, andSelfWithInterfaces(scoped) for the mapper, projector, request-mapper and update-applier families (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:53-80); the Infrastructure and UI composition roots each run oneImplementedInterfacesscan (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:139,MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:496). Both modes are exercised for every target and lifetime inMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DependencyInjection/ServiceCollectionDecorationDifferentialTests.cs:47.
ApplicationNamespace
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Configuration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/ApplicationNamespace.cs:35· Level 0 · class (static, partial)
What it is: the single shared value every piece of shared infrastructure is namespaced by: Redis cache keys, distributed-lock keys, distributed rate-limit counter keys, the Redis output-cache
InstanceName, the SignalR Redis backplane channel prefix, and the message broker's topic prefix (ApplicationNamespace.cs:7-12). Never empty, so isolation is automatic rather than a setting a host has to remember to set (:52-56). A broker host is the one exception to "never has to set it": there the value must be configured explicitly (:28-33).Depends on:
IConfigurationandIHostEnvironment(both optional parameters), and its own[GeneratedRegex]source-generated partial property (:49-50). BCL only.Concept: resolution with a fallback chain rather than a required setting.
[Rubric §11, Security]and[Rubric §7, Microservices Readiness]: two applications sharing one broker or one Redis instance used to share every keyspace by default, so a user-targeted push published in one application reached the other application's clients holding the same numeric user id (SEC-Common-53,ApplicationNamespace.cs:14-21). This type gives every consumer one namespace they can all agree on without each of them inventing its own default. The broker is where the fallback stops being safe: the host's application name differs per service, and every service of one application must publish and consume on the SAME topics, so a broker host has to state the value rather than inherit it (:28-33).Walkthrough: two public constants, one private constant, one generated regex, and two static methods.
ConfigurationKey = "Application:Namespace"(:38): the explicit override.Fallback = "app"(:41): used only when neither configuration nor the host environment names the application.HostApplicationNameKey = "applicationName"(:47): the key the generic host writes the application name to (HostDefaults.ApplicationKey,:43-46), read directly when noIHostEnvironmentis at hand.Resolve(configuration, environment)(:60-75): prefers the explicitConfigurationKey(sanitized); otherwise falls back toenvironment.ApplicationName, then to the rawapplicationNameconfiguration key; otherwise returnsFallback. Never returns empty.Sanitize(name)(:84-90): replaces every run of characters theUnsafeCharactersregex flags ([^a-zA-Z0-9_-]+,:49) with-, trims leading/trailing-, and returnsFallbackwhen nothing survives, because a Redis key tolerates almost anything while a broker queue or topic name and a SignalR channel prefix do not, and the whole point is one value every one of its consumers accepts (:77-81).
Why it's built this way: a value that is never empty means every consumer (cache key prefix, push channel prefix, rate-limit key) gets isolation whether or not a host ever sets
Application:Namespace, without asking every consumer to invent its own default. Override it only when two hosts of the SAME application must share a keyspace, such as a web head and a worker draining one backplane (ApplicationNamespace.cs:22-27).Where it's used: read by CacheKeyPrefixOptions's
CacheKeyNamespace.From(IServiceProvider)for the per-application default Redis key namespace (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheKeyPrefix.cs:126, withSanitizeat:129), by the notifications registration for the SignalR channel prefix (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:80), and by the distributed rate limiter's key namespace (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:223). On the broker pathAddBrokerMessagingfirst callsEnsureApplicationNamespaceConfigured, which throws whenConfigurationKeyis blank for a broker provider and names the setting to add (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:89,:270-278), then resolves the value and hands it to the BrokerConsumerBuilder and the BrokerTopology that prefix every topic (DependencyInjection.Messaging.cs:90-97). The keyspace isolation decision is ADR-135. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Configuration/ApplicationNamespaceTests.csandMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/DependencyInjectionBrokerMessagingTests.cs.
CloudAdapterTripwireOptions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Configuration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwireOptions.cs:8· Level 0 · class (internal sealed, empty)
What it is: an options type with no members. Its only job is to carry CloudAdapterTripwire through
ValidateOnStart, so that check runs with the other startup validators, before any hosted service starts (CloudAdapterTripwireOptions.cs:3-8).Depends on: nothing. It is declared as
internal sealed class CloudAdapterTripwireOptions;(CloudAdapterTripwireOptions.cs:8), a body-less class declaration.Concept: a marker options type used as a hook into the options validation pipeline.
ValidateOnStartonly runsIValidateOptions<T>validators for an options type somebody registered, so a check that validates the composed container rather than a configuration section still needs aTto hang on. An empty class is the cheapest suchT.[Rubric §15, Best Practices & Code Quality]scores moving failures to the earliest point: this is what places the cloud-adapter check at boot rather than at the first dropped push.Walkthrough: there is nothing to walk; the type has no members. The behavior lives in the two registration lines that use it:
services.AddOptions<Configuration.CloudAdapterTripwireOptions>().ValidateOnStart();and aTryAddEnumerableofIValidateOptions<CloudAdapterTripwireOptions>mapped to CloudAdapterTripwire (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:282-284).Why it's built this way: binding the tripwire to its own options type, rather than to an existing settings class, keeps the check independent of whether any particular section is present, and
TryAddEnumerablekeeps it to one validator even when several modules callAddInfrastructure. The fail-fast posture is ADR-070.Where it's used:
AddInfrastructure(DependencyInjection.cs:282-284) and the validator's generic argument (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwire.cs:32). Exercised byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Configuration/CloudAdapterTripwireTests.cs.
InProcessDistributedLock
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Concurrency·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/InProcessDistributedLock.cs:31· Level 1 · class (internal, sealed, partial)
What it is: the fallback
IDistributedLockfor a host with no Redis connection registered. It serializes callers inside this one process, and it says so in the log the first time anybody uses it.Depends on:
IDistributedLock(the contract it implements, fromMMCA.Common.Application.Interfaces, imported atInProcessDistributedLock.cs:4),ILogger<InProcessDistributedLock>injected through the primary constructor (InProcessDistributedLock.cs:31), and its own nestedInProcessLockHandle. BCL:ConcurrentDictionary,Interlocked,Stopwatch,Task.Delay.Concept introduced, the degraded implementation that announces itself.
[Rubric §12, Performance & Scalability]assesses whether the design survives horizontal scale-out: each replica gets its own instance of this class and therefore its own held-key table, so with more than one replica a section guarded by this lock still runs once per replica (InProcessDistributedLock.cs:11-15). That is correct for a single-replica deployment, for local development, and for tests, and wrong for anything else, which is why the fallback is not silent.[Rubric §13, Observability & Operability]assesses whether an operator can see a degraded mode: the first acquisition emits a[LoggerMessage]-generated warning that names both the cause and the fix (InProcessDistributedLock.cs:75-76, "noIConnectionMultiplexeris registered ... Register a Redis client (AddRedisClient) to make it exclusive across replicas").Walkthrough:
- State.
PollIntervalis 25 ms (InProcessDistributedLock.cs:34), the gap between acquisition attempts while waiting for a holder._heldis aConcurrentDictionary<string, byte>withStringComparer.Ordinal(InProcessDistributedLock.cs:36), used as a set: the value byte is a placeholder and only key presence matters._degradationWarnedis the warn-once flag (InProcessDistributedLock.cs:39). - Guards and the warning.
TryAcquireAsync(InProcessDistributedLock.cs:42-73) rejects a blank key, a non-positivettl, and a negativewait(InProcessDistributedLock.cs:48-50), then flips the flag withInterlocked.Exchange(ref _degradationWarned, 1) == 0so a steady state warns once rather than per request (InProcessDistributedLock.cs:52-55). - The acquire loop (
InProcessDistributedLock.cs:59-72)._held.TryAdd(key, 0)is the atomic test-and-set: it succeeds only for the caller that inserts the key, and that caller gets anInProcessLockHandle(InProcessDistributedLock.cs:61-63). Otherwise, ifStopwatch.GetElapsedTime(startedAt) >= waitthe method returnsnull(InProcessDistributedLock.cs:66-69), which is what makeswait: TimeSpan.Zeroa single non-blocking attempt exactly as the contract promises. Otherwise it awaitsTask.Delay(PollInterval, cancellationToken)and retries (InProcessDistributedLock.cs:71). - Exact keys, not stripes. The remarks explain the one design choice that differs from
KeyedSemaphoreStripe(InProcessDistributedLock.cs:18-25): stripes let two unrelated keys share a semaphore, which is harmless for a caller that waits indefinitely but not for a bounded wait, where the false sharing turns into a spurious "held elsewhere" answer for a key nobody holds. The table stays bounded by the number of locks held right now, not by every key the process has ever seen, because the handle removes the entry on release. ttlis accepted and ignored (InProcessDistributedLock.cs:26-29). It is validated (InProcessDistributedLock.cs:49) but never used: the TTL exists to bound a holder that died without releasing, and here the holder is a task in this process, so if the process dies the table dies with it.
- State.
Why it's built this way: ADR-017 makes the lock a registration rather than an optional dependency, so a host always resolves something; this type is the honest floor of that guarantee. Logging the degradation once, instead of silently behaving like a lock, is what keeps "we have a distributed lock" from becoming a false belief in a multi-replica deployment.
Where it's used: registered by
AddCachingin the Infrastructure composition root when noIConnectionMultiplexeris resolvable (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:126-128, inside theIDistributedLockfactory at:84-98; seeDependencyInjection), which covers MMCA.Helpdesk, local single-process runs, and tests. Behavior is pinned byInProcessDistributedLockTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Concurrency/InProcessDistributedLockTests.cs:12).
UseDataSourceAttribute
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/UseDataSourceAttribute.cs:14· Level 1 · class (sealed attribute)
What it is: the companion attribute to
UseDatabaseAttribute. Where that one names the logical database, this one declares the database engine (DataSource:CosmosDB,Sqlite, or SQL Server) an entity type configuration targets. It is Level 1 rather than Level 0 because, unlike the pure-BCLUseDatabaseAttribute, it references the first-partyDataSourceenum.Depends on: the
DataSourceenum (fromMMCA.Common.Application.Interfaces.Infrastructure.Persistence, imported atUseDataSourceAttribute.cs:1) andSystem.Attribute(BCL).Concept: engine selection for the multi-engine persistence layer, the sibling of the logical-name routing introduced under
UseDatabaseAttribute.[Rubric §8, Data Architecture]again: the framework supports SQL Server, Cosmos, and SQLite simultaneously, and this attribute is how a configuration announces which engine's rules apply. In practice it is carried on the provider-specific configuration base classes (EntityTypeConfigurationSQLServer/Cosmos/Sqlite), so a concrete configuration inherits its engine, whileUseDatabaseAttributeselects which database on that engine.Walkthrough:
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)](UseDataSourceAttribute.cs:13), same inheritance and single-use semantics asUseDatabaseAttributeso a provider base class propagates the engine to derived configurations.- Primary-constructor parameter
dataSource(UseDataSourceAttribute.cs:14) of typeDataSource. DataSourceget-only property (UseDataSourceAttribute.cs:17) exposing the chosen engine. The XML doc (UseDataSourceAttribute.cs:5-11) records that it is read byDataSourceServiceat model-building time to populate the entity-to-data-source cache thatUnitOfWorkuses to route each entity to the correctApplicationDbContext.
Why it's built this way: keeping the engine on an attribute (inherited from a provider base class) means an entity's engine and database are both declarative metadata the registry can scan up front, which is what lets routing happen without first building an EF model (ADR-006).
Where it's used: on the per-engine
EntityTypeConfiguration*base classes and, through inheritance, every concrete configuration under them; read byDataSourceService/EntityDataSourceRegistry.
ServiceCollectionDecoration
MMCA.Common.Application, MMCA.Common.Infrastructure, MMCA.Common.UI (linked source) ·
MMCA.Common.DependencyInjection·MMCA.Common/Source/Build/DependencyInjection/ServiceCollectionDecoration.cs:47· Level 1 · class (internal, static)
What it is: the framework's own assembly scanning and decoration over
IServiceCollection, with no third-party dependency (ServiceCollectionDecoration.cs:20-24). It is one internal source file compiled into each project that scans or decorates, through a linked<Compile Include>(MMCA.Common/Source/Core/MMCA.Common.Application/MMCA.Common.Application.csproj:14,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:11,MMCA.Common/Source/Presentation/MMCA.Common.UI/MMCA.Common.UI.csproj:34), so each of those assemblies carries a private copy and none of it is public API.Depends on:
ScanRegistrationandDecorationKey(both Level 0, same file). Externals:Microsoft.Extensions.DependencyInjection(ServiceDescriptor, keyed services,ActivatorUtilities) andSystem.Reflection.Concept introduced, decoration by keyed relocation. A decorator wraps a registered service in another implementation of the same interface; the CQRS pipeline in the primer is built this way (ADR-014). The container has no native "wrap" operation, so this class moves the original registration to a private keyed copy with the same lifetime (the container still owns its creation and disposal) and replaces it in place with a factory that activates the decorator over that copy (
:27-29). Because the replacement sits at the original's index, "last registration wins" andIEnumerable<T>order are unchanged (:29-30). Decorating again wraps the previous decorator, so the decorator applied last is the outermost at runtime (:30-31), which is whyAddApplicationDecoratorswalks its outermost-first list backwards (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:398-409).[Rubric §2, Design Patterns]assesses whether patterns are applied deliberately: here Decorator is realized at the composition root, so handlers never know they are wrapped.[Rubric §32, Dependency & Supply-Chain]assesses how much third-party code the product trusts: the class replaces a container-extension package with about 260 lines of owned code, and that package survives only as a test oracle (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DependencyInjection/ServiceCollectionDecorationDifferentialTests.cs:15-20).Walkthrough
AddAssignableTypes(services, assembly, assignableTo, registration, lifetime)(:59-106): null-guards its inputs (:66-68), then keeps every defined type that passesIsScannableClass(public or nested-public, a non-abstract class, not special-name, not compiler-generated,:251-256) andIsAssignableTo(:258-279), where an open generic target matches a closed implementation on the class's interfaces or anywhere up its base-type chain. InSelfWithInterfacesmode it runs two passes, every self registration before any interface (:75-95), with interface registrations built as forwarding factories throughForwardTo(:90,:248-249); open generic classes skip the interface pass (:84-86). InImplementedInterfacesmode each interface maps straight to the class (:97-103).ServiceInterfaces(:243-246) keeps only interfaces whose generic arity matches an open generic class (HasMatchingGenericArity,:281-291) and registers them by their open definition (RegistrationType,:293-296). Registrations are appended, never de-duplicated (:44).TryDecorateWith(services, serviceType, decoratorType)(:115-129): the type-based overload. An open generic decorator is closed over each matched registration's type arguments (:123-125) and activated withActivatorUtilities.CreateInstance, passing the wrapped instance as a constructor argument (:127). Returnstruewhen at least one registration was decorated.TryDecorateWith<TService, TDecorator>()(:136-138) forwards to the type-based overload;TryDecorateWith<TService>(Func<TService, IServiceProvider, TService>)(:145-155) decorates with a factory instead of a type.DecorateWith<TService, TDecorator>()(:166-177): the strict form, throwingInvalidOperationExceptionwith "Register the service before decorating it." when nothing matched (:169-174).DecorateEach(:179-208), the private core. It first collects matching indices (:184-191), then for each one mints a freshDecorationKey(:197), adds the original back as a keyed registration (:200) and overwrites the index with an unkeyed factory of the original lifetime that resolves the keyed copy and activates the decorator over it (:201-204).Matches(:210-225) skips keyed registrations, matches a closed service type exactly, and matches an open generic service type against every closed registration of it.AsKeyed(:227-241) preserves the original's shape: implementation type, instance, or factory.
Why it's built this way: an open generic registration such as
AddScoped(typeof(IHandler<,>), typeof(Handler<,>))cannot be wrapped, because the container has no open generic factories; it is left untouched and the pipeline'sVerifyDecoratorPipelinereports it rather than letting it run undecorated (:34-38). Linking one internal source file instead of shipping a public helper keeps the mechanism out of every package's public surface.Where it's used: the CQRS pipeline and profiling pair (
MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:239-240,:407, seeProfilingCommandDecorator<TCommand, TResult>); module scanning (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:53-80); Infrastructure decorations ofLayeredPermissionRegistry(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:216), the feature-definition provider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:80) andImpersonatingCurrentUserService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:323); and the UI'sPseudoStringLocalizerFactoryvia the strictDecorateWith(MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:124).RegistrationGraphSnapshotrecognizes its factories by type name, since a linked internal source cannot be matched by assembly (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Registrations/RegistrationGraphSnapshot.cs:152-168). Its behavior is pinned against the third-party oracle byServiceCollectionDecorationDifferentialTests(scan graphs at:47, open generic, closed and factory decoration at:103,:128,:147, the unregistered case at:162).Caveats / not-in-source: because the file is compiled into three assemblies, each has its own
ServiceCollectionDecorationtype; they are identical by construction, not by a shared reference.
RedisDistributedLock
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Concurrency·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/RedisDistributedLock.cs:24· Level 2 · class (internal, sealed, partial)
What it is: the cross-replica
IDistributedLock, implemented as the standardSET key token NX PX ttlRedis lock against a single Redis instance.Depends on:
IConnectionMultiplexerand the rest of StackExchange.Redis (IDatabase,RedisKey,RedisValue,RedisResult),ILogger<RedisDistributedLock>, and an optionalCacheKeyNamespace(RedisDistributedLock.cs:24-27), which is what puts this type at Level 2 rather than Level 1. It returns its nestedRedisLockHandle.Concept: the acquire half of the lock taught in two pieces with
RedisLockHandle.[Rubric §12, Performance & Scalability]assesses scale-out correctness: moving the lock into Redis is what makes "only one of these runs at a time" true across replicas instead of true per process, which is the whole reason the abstraction exists (seeInProcessDistributedLockfor the degraded alternative).[Rubric §29, Resilience & Business Continuity]assesses failure behavior: the expiry carried on theSETis the crash guard (a holder that dies releases by expiry rather than wedging the key forever,RedisDistributedLock.cs:12-17), and the class documents that it is deliberately single-instance, not Redlock (RedisDistributedLock.cs:19-23), inheriting Redis's failover behavior, which is exactly why the contract is documented as best-effort. The release side honors the same posture: a fault while releasing is caught and logged by the handle (RedisDistributedLock.cs:124-129, seeRedisLockHandle) rather than failing the already-committed guarded work.Walkthrough:
- State.
KeyPrefixis"lock:"(RedisDistributedLock.cs:30) so lock entries cannot collide with cache entries in a shared instance.ReleaseScript(RedisDistributedLock.cs:36-37) is the compare-and-delete Lua taught underRedisLockHandle.PollIntervalis 50 ms (RedisDistributedLock.cs:40); unlike the in-process poll, each retry here is a network round trip._keysfalls back toCacheKeyNamespace.Nonewhen no namespace was injected (RedisDistributedLock.cs:42), so theCache:KeyPrefixoption (when configured) qualifies lock keys the same way it qualifies cache keys. - Argument guards.
TryAcquireAsync(RedisDistributedLock.cs:45-82) applies the same three checks as the in-process implementation: non-blank key,ttlgreater than zero, non-negativewait(RedisDistributedLock.cs:51-53). - Key and token. The physical key is
_keys.Qualify(string.Concat(KeyPrefix, key))(RedisDistributedLock.cs:55). The token is a freshGuid.NewGuid().ToString("N", CultureInfo.InvariantCulture)minted per acquisition (RedisDistributedLock.cs:59); the release script matches on it, and that is what makes a release owner-scoped instead of "delete whatever is there now" (RedisDistributedLock.cs:57-58). - The acquire loop (
RedisDistributedLock.cs:64-81).StringSetAsync(redisKey, token, ttl, keepTtl: false, When.NotExists, CommandFlags.None)(RedisDistributedLock.cs:66-68) is a single atomic conditional set carrying the expiry, so exactly one replica can win a key. On success it returns aRedisLockHandleclosing over the database, key, token, and logger (RedisDistributedLock.cs:70-73); onceStopwatch.GetElapsedTime(startedAt) >= waitit returnsnull(RedisDistributedLock.cs:75-78); otherwise it delays onePollIntervaland retries (RedisDistributedLock.cs:80).
- State.
Why it's built this way: ADR-017 replaced the process-local guard around the idempotency filter's execute-then-store window with this, because a striped semaphore stops serializing anything once a service runs more than one replica. Choosing the one-instance
SET NX PXlock over Redlock is a stated trade: simpler, dependent on a single Redis, and paired with a contract that tells callers never to lean on it for an invariant persistence can enforce.Where it's used: selected by
AddCachingwhenever anIConnectionMultiplexeris resolvable (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:115-129, seeDependencyInjection), passing the sameCacheKeyNamespacethe distributed cache gets (DependencyInjection.Caching.cs:88,:91). The one in-framework caller is the APIIdempotencyFilter;RedisDistributedLockTestscovers the acquire and release commands against a mockedIDatabase.Caveats / not-in-source: whether a given deployed environment actually supplies the
redisconnection string is an infrastructure/config fact, not a source fact, so "which implementation is live in environment X" is Not determinable from source here; the source only settles that the presence of a registeredIConnectionMultiplexerdecides it.
CloudAdapterTripwire
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Configuration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwire.cs:32· Level 4 · class (internal sealed)
What it is: a startup validator that fails the host when configuration switches on a capability whose implementation lives in a package or registration call that never ran, so the inert core default is still in place (
CloudAdapterTripwire.cs:12-14). It checks three switches: passkeys, machine clients and native push.Depends on:
IValidateOptions<CloudAdapterTripwireOptions>(CloudAdapterTripwire.cs:32), with CloudAdapterTripwireOptions as the empty carrier type; the rootIServiceProvideras its single primary-constructor parameter;IConfiguration(resolved from that provider); IPasskeyCeremony, IMachineClientService, INativePushSender and its core no-op NullNativePushSender (:4-8).Concept introduced: a tripwire on a quiet default. The core packages are cloud-neutral, so native push resolves to
NullNativePushSenderuntil an adapter swaps it, and that default is deliberately quiet: a push is dropped (CloudAdapterTripwire.cs:16-18). Quiet is right for a host that never switched push on and wrong for one that did, because a deployment that setsNativePush:Enabledbut lost the adapter call would start, pass its health checks and silently stop delivering pushes (:18-21). The opt-in passkeys and machine-client features fail the same quiet way: an enabled section without its registration call leaves every one of their routes answering 404 (:37-41,:44-48).[Rubric §13, Observability & Operability]and[Rubric §15, Best Practices & Code Quality]: the tripwire turns each silent loss into a boot failure whose message names the missing call. The cloud-neutral core is ADR-134, native push is ADR-044, passkeys are ADR-139 and machine clients are ADR-140.Walkthrough:
- Three internal key constants, so the tests can name them:
NativePushEnabledKey = "NativePush:Enabled"(CloudAdapterTripwire.cs:35),PasskeysEnabledKey = "Passkeys:Enabled"(:42) andMachineClientsEnabledKey = "MachineClients:Enabled"(:49). Validate(name, options)(:52-86) resolvesIConfigurationand returnsValidateOptionsResult.Skipwhen there is none (:54-58), then collects failures inside a created scope (:62), so it sees each service the way a request would.- Passkeys (
:64-69): fails when the switch is on and noIPasskeyCeremonyresolves, namingservices.AddPasskeys(configuration)fromMMCA.Common.PasskeyswithPasskeys:RelyingPartyIdandPasskeys:Origins. - Machine clients (
:71-75): fails when the switch is on andIMachineClientServiceis not registered, namingservices.AddMachineClients(configuration)and the app'sIServiceAccountProvisioner. A missing provisioner is left to the settings validator that call registers (:47-48). - Native push (
:77-82): fails when the switch is on and the resolvedINativePushSenderis absent or stillNullNativePushSender. The message lists the three adapter paths with their registration calls and required keys:AddAzureNotificationHubsPushfromMMCA.Common.Azure,AddAmazonSnsPushfromMMCA.Common.Aws, andAddFirebaseCloudMessagingPushfromMMCA.Common.Gcp. - It returns
Successwhen no failure was collected, otherwiseFail(failures)(:85), so one boot reports every missing call at once. - Two private helpers:
IsSwitchedOn(:92-93) is true only when the key parses astrue, andIsRegistered<TService>(:99-100) asksIServiceProviderIsServicewithout constructing the service (treating an unanswerable provider as registered).
- Three internal key constants, so the tests can name them:
Why it's built this way: a tripwire must fire on a key that declares intent, so file storage deliberately has no check. A
FileStoragesection is routinely shared configuration (one user-secrets id across every service of a solution), so a host that never stores files sees it too, and a host that does store files and lost its adapter call is not silent anyway: NullFileStorageService fails every upload withFileStorage.NotConfigured(CloudAdapterTripwire.cs:23-29). Running as an options validator underValidateOnStartplaces the check with the other startup validators, before any hosted service starts, the fail-fast contract of ADR-070.Where it's used: registered once in
AddInfrastructurethroughTryAddEnumerable(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:283-284). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Configuration/CloudAdapterTripwireTests.cs, and the machine-client branch also byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/MachineClients/AddMachineClientsTests.cs.
StartupConfigurationSummaryService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Configuration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/StartupConfigurationSummaryService.cs:35· Level 11 · class (internal sealed partial,IHostedService)
What it is: a hosted service that writes one Information line at host start naming the posture the host actually resolved: the MMCA.Common version, the database engines it configures, the message bus transport with its
ProvisionTopologyvalue, the cache mode and the tenancy mode. A support question ("which version, which bus, which cache?") is then answered by the first lines of the log rather than by reading the deployed configuration (StartupConfigurationSummaryService.cs:14-19).Depends on: six primary-constructor parameters (
StartupConfigurationSummaryService.cs:35-41):IOptions<ConnectionStringSettings>(ConnectionStringSettings), DataSourcesSettings,IOptions<MessageBusSettings>(MessageBusSettings),IOptions<TenancySettings>(TenancySettings), the rootIServiceProvider, andILogger<T>. It calls DataSourceResolver.ResolveConfiguredEngines, and checks forHybridCache,IDistributedCacheandMemoryDistributedCachefrom the Microsoft caching packages (:2-3).Concept introduced: log the resolved posture, never the configuration text.
[Rubric §13, Observability & Operability]scores whether a running system can be understood from outside. Several of the settings it reports resolve from more than one source (a transport name that may be an adapter's, a cache tier picked by registrations, a tenancy mode implied by per-tenant data sources), so the configured values alone do not say what the host is doing; this line does.[Rubric §11, Security]: only names, enum values and flags are logged. Connection strings, keys and every other secret stay out, and the engines are derived from WHETHER a connection string is set, never from its text (StartupConfigurationSummaryService.cs:20-23).Walkthrough:
FrameworkVersion(StartupConfigurationSummaryService.cs:49-52): theAssemblyInformationalVersionAttributestamped on the assembly (the release tag on a release build, the0.0.0-devplaceholder otherwise), orunknownwhen it is absent, computed once in a static property.StartAsync(:55-77) builds the summary only when Information is enabled (:59), so a host that filters Information pays nothing for the engine and cache probes. It names the engines (nonewhen there are none,:61-62), the cache mode and the tenancy mode, and writes them with the busProviderandProvisionTopologythrough the source-generatedLogConfigurationSummary(:66-73, declared at:127-137). It writes nothing else.StopAsync(:80) is a completed task.CacheMode(services)(:95-107) returnshybridwhenHybridCacheis registered,misconfiguredwhen the resolvedIDistributedCacheis not the in-memoryMemoryDistributedCache(the host wired Redis but not the cache over it, which theAddCachingfactory refuses on first use), andmemoryotherwise. It deliberately repeats the decision theICacheServiceregistrations make instead of resolving ICacheService, because the two-level cache resolvesIConnectionMultiplexerand constructing it here would open a Redis-backed host's connection at startup instead of on first use;HybridCacheis checked by registration throughIServiceProviderIsService, and resolvingIDistributedCachedoes not connect (:82-94).TenancyMode(settings)(:115-125) returnsoffwhen tenancy is disabled,database-per-tenantwhen at least one tenant routes a data source to its own database, andshared-databaseotherwise.
Why it's built this way: the summary is one line so it sits at the top of every log. Naming a
misconfiguredcache up front surfaces at boot a state that would otherwise fail only on the first cache use. Registration throughTryAddEnumerablemeans a host whose modules each callAddInfrastructurestill writes the summary exactly once (StartupConfigurationSummaryService.cs:24-27).Where it's used: registered in
AddInfrastructurewithTryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, Configuration.StartupConfigurationSummaryService>())(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:276).CacheModeandTenancyModeareinternal staticso the tests can call them directly. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Configuration/StartupConfigurationSummaryServiceTests.cs.Caveats / not-in-source: no ADR records this service. The line is written once at start, so a setting changed at runtime through a reloadable provider is not reflected in it.
DependencyInjection
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:20· Level 16 · class (static, extension, partial)
What it is: the single composition root for the entire Infrastructure layer. A
static partial classsplit across nine files by concern (DependencyInjection.cs,.Auth.cs,.Caching.cs,.FeatureFlags.cs,.Jobs.cs,.MachineClients.cs,.Messaging.cs,.Notifications.cs,.Persistence.cs), each carrying its own C# previewextension(IServiceCollection services)block, so the registration surface reads as one type while the methods live next to the settings and services they wire.DependencyInjection.cscarriesAddInfrastructure(IConfiguration)(DependencyInjection.cs:59),AddMultiTenancy(IConfiguration)(:347),AddServices()(:373),AddEntityConfigurationAssembly(Assembly)(:432) andAddStronglyTypedIds(params Assembly[])(:460), plus the internalAddRawSqlQueryExecutorhelper below its extension block (:485);.Caching.cscarriesAddCaching(IConfiguration?)(DependencyInjection.Caching.cs:29),AddCommonHybridCache(Action<HybridCacheOptions>?)(:189),AddCommonHybridCacheWhenRedisConfigured(IConfiguration, string)(:255) andAddRedisConfigurationOptionsConfigurator(IRedisConfigurationOptionsConfigurator)(:282), plus the privateEnsureSharedDistributedCacheRegisteredhelper (:303);.FeatureFlags.cscarriesAddReloadableFeatureFlags(IConfiguration, params Assembly[])(DependencyInjection.FeatureFlags.cs:49);.Jobs.cscarriesAddScheduledJobs(IConfiguration)(DependencyInjection.Jobs.cs:37),AddScheduledJob<TJob>()(:76) andAddAuditTrail(IConfiguration)(:112), plus the privateAddInternalCommandshelper (:150);.MachineClients.cscarriesAddMachineClients(IConfiguration)(DependencyInjection.MachineClients.cs:38);.Notifications.cscarriesAddNotificationInfrastructure(IConfiguration)(DependencyInjection.Notifications.cs:29) andAddPushNotifications(IConfiguration)(:62);.Messaging.cscarriesAddBrokerMessaging(IConfiguration, Action<IBrokerConsumerBuilder>?)(DependencyInjection.Messaging.cs:63) andAddBrokerTransport(IBrokerTransport)(:180), plus four private static helpers below its extension block (:205,:254,:276,:299);.Persistence.cscarriesAddNpgsqlDataSourceConfigurator(INpgsqlDataSourceConfigurator)(DependencyInjection.Persistence.cs:24); and.Auth.cscarries the five opt-in identity completions (DependencyInjection.Auth.cs:20-232). Native push and blob storage registration no longer live here: the vendor implementations are registered by the adapter packages (DependencyInjection.cs:421-433, ADR-134).Depends on: nearly every Infrastructure type below it, wired by interface. Persistence:
DbContextFactory,PhysicalDbContextFactory,DataSourceService,DataSourceResolver,EntityDataSourceRegistry,FrameworkTableTargets,DefaultEntityConfigurationAssemblyProvider,EFQueryableExecutor,SqlServerUniqueConstraintViolationDetector,EFRepository<TEntity, TIdentifierType>,RepositoryFactory,UnitOfWork,AuditSaveChangesInterceptor,DomainEventSaveChangesInterceptor,TenantSaveChangesInterceptor,INpgsqlDataSourceConfigurator,InternalCommandProcessor. Messaging/outbox:IMessageBus/InProcessMessageBus/BrokerMessageBus,IEventBus/InProcessEventBus/BrokerEventBus,OutboxSignal,OutboxProcessor,OutboxCleanupService,OutboxDisabledNoticeService,OutboxAdministration,EfInboxStore/NoOpInboxStore/InboxDisabledWarningService,IBrokerTransportwithRabbitMqBrokerTransport/PostgreSqlBrokerTransport,BrokerTransportContext,MessageBusProviders. Cross-cutting:ICacheServicewithMemoryCacheService/HybridCacheService,CacheKeyNamespace,IDistributedLockwithRedisDistributedLock/InProcessDistributedLock,IJwksProvider/RsaJwksProvider,TokenService,LoginProtectionService,PasswordResetTokenService,AuthSessionIssuer,UserSessionsAdministrationService,EFRefreshSessionStorewithRefreshSessionCleanupService,TotpTwoFactorService,TwoFactorAuthenticator,EmailConfirmationTokenService,IModelContributor/PermissionGrantModelContributor,EFPermissionGrantStore,PermissionGrantCache,PermissionGrantRefreshService,StoredPermissionRoleAdministrationService,LayeredPermissionRegistry,ClaimBasedUserIdProvider,EventUpcasterStartupValidator,StartupConfigurationSummaryService,CloudAdapterTripwirewithCloudAdapterTripwireOptions,ScheduledJobRunner,IAuditTrailReader/AuditTrailReader,AuditTrailCleanupJob,TenantContext,CorrelationContext,NullPushNotificationSender/NullLiveChannelPublisher,NullNativePushSender,NullPushDeviceRegistrar,NullFileStorageService. Settings:ConnectionStringSettingswithConnectionStringSettingsValidator,DataSourcesSettings/DataSourceEntrySettings,MessageBusSettings,OutboxSettings,PersistenceSettings,SmtpSettings,JwksSettings,CacheSettings,QueryCachePipelineSettings,LoginProtectionSettings,PasswordResetSettings,RefreshSessionSettings,LegalAcceptanceOptions,SchedulerSettings,AuditTrailSettings,TenancySettingswithTenancySettingsValidator,PushNotificationSettings. Externals:RabbitMQ.Clientfor the built-in RabbitMQ transport (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:49; there is no messaging library between the framework and the broker SDKs since MassTransit was removed in v1.316.0, ADR-118), StackExchange.Redis,Microsoft.Extensions.Caching.Hybrid,Microsoft.AspNetCore.SignalR, Npgsql. Assembly scanning and decoration use the framework's own linkedServiceCollectionDecorationrather than a container-extension package. No cloud vendor SDK: those live in the adapter packages (ADR-134).Concept introduced, the mega-composition-root plus the swap-at-the-edge extraction pattern.
[Rubric §3, Clean Architecture]assesses whether wiring lives at the edge rather than in the core: every concrete Infrastructure choice is registered here, not in Application or Domain.[Rubric §12, Performance & Scalability]and[Rubric §7, Microservices Readiness]: the method bodies are the framework's default posture, and each optional capability (broker, scheduler, audit trail, tenancy, hybrid cache, push, the identity completions) is a separate opt-in method a host layers on, so the same package runs as a monolith or as an extracted service without recompiling the core. The default everywhere isTryAdd*, meaning a host can pre-register its own implementation and the framework will not clobber it; the places that deliberately break that rule are the broker swap (Replace,DependencyInjection.Messaging.cs:128and:134),AddCommonHybridCache(RemoveAll,DependencyInjection.Caching.cs:223), andAddPushNotifications, which appends the SignalR senders over their null defaults (DependencyInjection.Notifications.cs:97-98) andReplaces SignalR's ownIUserIdProvider(:67), and each says so in a comment.[Rubric §17, DevOps]: registering a capability is consistently NOT the same as enabling it: the scheduler and the audit trail both stay inert until theirEnabledflag is true (DependencyInjection.Jobs.cs:32-34,:89-92), and the internal-command processor runs only underInternalCommands:Enabled(:174-183), so a host ships the registration and an environment turns it on.[Rubric §15, Best Practices & Code Quality]: the places where a misconfiguration would be silent instead throw or warn at startup, which is the running theme of this file.Walkthrough (in registration order):
AddInfrastructure(DependencyInjection.cs:59-315) is the entry point. It registers the model-facing singletons (:61-62) and the three EF save interceptors as singletons because they are stateless with per-save state in aConditionalWeakTablekeyed by context (:64-72), includingTenantSaveChangesInterceptor, which is registered unconditionally so a host can never leave the write-side tenancy guard half-wired (:69-72). It registersFrameworkTableTargetsonce (:98), the set of databases the framework table sweeps (outbox, internal commands, audit trail) visit, and bindsSmtpSettingswith validation (:100-103). The raw-SQL executor goes through the internalAddRawSqlQueryExecutorhelper (:118), which registersIRawSqlQueryExecutoronly when the default source is on a relational engine, so a Cosmos-default host fails at resolution rather than on its first statement (:475-498); it is scoped because it reaches the scope's own context throughIDbContextFactory, sharing the caller's connection and any open transaction (:115-117).IConcurrencyConflictDetector/EfCoreConcurrencyConflictDetectorisTryAddSingleton(:128), the sibling classifier to the unique-constraint detector for a save rejected by a moved concurrency token. The explicit audit-trail writerIAuditTrailWriteris always registered scoped, inert untilAddAuditTrailandAuditTrail:Enabledput the trail table in the model (:134-137). Near the end it calls the privateAddInternalCommandshelper (:301, ADR-114), thenAddServices()(:303), then decoratesICurrentUserServicewithImpersonatingCurrentUserServiceviaTryDecorateWith(:305-312), guarded on whetherScopedUserOverrideis already registered so a host whose modules each callAddInfrastructuredoes not stack one decorator per call.- Settings binding, and the one rule annotations cannot express.
ConnectionStringSettingsbinds throughAddOptions(...).ValidateDataAnnotations().ValidateOnStart()(:74-77), thenConnectionStringSettingsValidatoris added throughTryAddEnumerable(:84-85) with the reason inline (:79-83): "a host must reach some database" spans theConnectionStringssection AND theDataSourcesone, so a SQLite-only host declaring its databases as named sources is legitimate while a host declaring none anywhere is not. The sameTryAddEnumerableidiom recurs for every validator and startup check in the file, so two modules callingAddInfrastructurenever run one validation twice. - The named-data-sources note (
:87-91) is load-bearing:DataSourcesSettingsis built directly fromconfiguration.GetSection(...).Get<Dictionary<string, DataSourceEntrySettings>>()rather than throughAddOptions, because a root-level dictionary section does not bind through the options pipeline. The resolver and the eager entity registry follow immediately (:93-94). - The physical-factory warning (
:105-111):DbContextFactoryis scoped (one per request) andPhysicalDbContextFactoryis a singleton that must never be converted to EF context pooling, because each raw context carries per-source constructor state that pooling would silently reuse across databases. Beside them sit the stateless query executor (:113) and the unique-constraint classifier (:120-123), the latterTryAdded so a host on another engine can register its own first and keep it. - The assembly scan (
:139-145) discovers everyIEntityTypeConfigurationBase<TEntity, TIdentifierType>in the Infrastructure assembly through the framework's ownAddAssignableTypes(ServiceCollectionDecoration) overtypeof(ClassReference).Assembly(:141-142) and registers each as its implemented interfaces (ScanRegistration.ImplementedInterfaces,:144), scoped to match the DbContext lifetime, closing the loop back toClassReference.AddCaching(configuration)is called immediately after (:147), followed by thePersistenceSettingsandOutboxSettingsbindings (:151-159). - The auth block (
:161-233) bindsLoginProtectionSettings,PasswordResetSettingsandRefreshSessionSettingswith their scoped services, registersAuthSessionIssuerscoped (it issues, rotates and revokes the token pair,:192-194) and the administrator's read-onlyUserSessionsAdministrationServicescoped (:196-198), and gates one hosted service:RefreshSessionCleanupServiceis registered only whenRefreshSessions:Enabledis true (:229-233), on the same flag that maps the table. The comment names the failure it avoids (:225-228): an unconditional registration would start a periodic sweep (everyCleanupIntervalHours, default 6) in every service of a modular host, all but one of which has no table to sweep. The same block registers three optional-table model contributors throughTryAddEnumerable(ADR-148): the refresh-session one (:181-185), the view-as grant one beside the always-boundViewAsSettingsand the scoped view-as store and service (ADR-137,:200-212), and the passkey credential one beside the scoped passkey store (ADR-139,:214-223), each inert until its own settings enable the table; it also adds the refresh-session section of the data-subject export (:187-190).MessageBusSettingsandJwksSettingswithRsaJwksProviderfollow (:235-244). - Four startup checks (
:246-272), each added throughTryAddEnumerable.EventUpcasterStartupValidator(:250-251) fails the host at start on a duplicate source, a self-map or a cycle rather than dead-lettering the first retired-contract message (ADR-090).NavigationPopulatorStartupValidator(:257-258, declared atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:36) fails the host at start on a navigation the data source cannot include (cross-database, non-relational, or an unmapped target) that noINavigationPopulatorloads, instead of every read with includes returning it empty; a host whose navigations all share one relational database resolves nothing (:253-256).StartupConfigurationSummaryService(:263-264) writes one Information line per host start naming the resolved posture (version, engines, bus with itsProvisionTopologyvalue, cache, tenancy) (:260-262).CloudAdapterTripwirevalidatesCloudAdapterTripwireOptionson start (:270-272): an enabledNativePushsection whose sender still resolves to the inert core default means the vendor adapter call is missing, so the host fails naming the call instead of running with pushes dropped (:266-269). - The outbox is a transport decision (
:274-299).OutboxSignalis always registered (:274). Then the message-bus section is read eagerly (:282-283), passed to the privateEnsureOutboxAvailableForProviderguard (:284), andMessageBusSettings.IsOutboxEnableddecides between the two hosted outbox services (OutboxProcessorplusOutboxCleanupService,:286-290) and a singleOutboxDisabledNoticeService(:293). The comment states the trade in full (:276-281): a broker deployment cannot deliver without the outbox, while a single-process host would pay two hosted services, a table and a poll loop for a hop it never takes, and theOutboxMessagestable stays mapped either way so flipping the flag is never a migration (ADR-100). The operator surfaceOutboxAdministrationis scoped, because it creates one child scope per data source it visits (:296-299). AddInternalCommands(DependencyInjection.Jobs.cs:150-188) mirrors the outbox posture: it bindsInternalCommandsSettings, registers the signal, the origin capture andIInternalCommandSchedulerscoped on the caller's own context factory so scheduling is atomic with the aggregate change (:158-162), and the operator surfaceIInternalCommandAdministration(:164-167). OnlyInternalCommands:EnabledaddsInternalCommandProcessorplus its cleanup service; otherwise a disabled-notice service (:174-183). The table is mapped unconditionally, so the flag never implies a migration (:135-138).AddCaching(DependencyInjection.Caching.cs:29-149) does two probes in one method, and itsIConfigurationparameter is optional. With configuration it binds the key-prefix options plusCacheSettingsand the Application layer'sQueryCachePipelineSettings(:44-57); without it, both are registered bare soIOptions<T>still resolves to framework defaults instead of failing a host that called the parameterless overload (:58-62, with the reasoning at:34-43). It post-configuresRedisOutputCacheOptions.InstanceNameto the same key namespace (CacheKeyNamespace.From(sp),:75) when the host left it empty, so two applications on one Redis do not share output-cache entries or tag sets (:64-77, ADR-135). The cache (:79-99):AddCachingregisters only the in-processMemoryCacheService(:96-98), where the keyspace is private to the process so no prefix is needed. A shared distributed cache is served only byHybridCacheService, whichAddCommonHybridCacheregisters in place of this one (:162-208), so if anIDistributedCacheis registered and is not the no-opMemoryDistributedCachewhen this factory runs, it throws anInvalidOperationExceptionnamingAddCommonHybridCacherather than silently falling back to a per-replica cache (:86-93). The lock:RedisDistributedLockwhen a multiplexer resolves, keyed by theCacheKeyNamespace(:111-118),InProcessDistributedLockotherwise (:120-122). The comment explains why the lock is registered next to the cache at all (:101-108): all five in-framework callers pair the two (the API idempotency filter, password-reset token redemption, the two-factor authenticator's last-accepted time step,OAuthControllerBase's read-and-burn of a single-use exchange code, andPasskeyChallenges' challenge redemption and passkey deletes).AddCommonHybridCache(DependencyInjection.Caching.cs:195-243) is the opt-in two-level cache (ADR-077). It callsAddHybridCache(:160), then configuresHybridCacheOptionsthrough the options pipeline rather than theAddHybridCachecallback (:166-180), because the TTL policy comes from the boundCachesection and the callback has no service provider to read it from (:162-165); the host's own hook runs last so it can override anything the framework set (:179). It then deliberately doesRemoveAll<ICacheService>()beforeAddSingleton(:184-198) so the call wins whether it runs before or afterAddInfrastructure. The remarks are honest about the cost of that choice (:147-151):RemoveAlldoes not distinguish the framework's registration from a host's own customICacheService, so calling this is a statement that the two-level cache IS the cache.AddCommonHybridCacheWhenRedisConfigured(:219-231) is the guarded form: it callsAddCommonHybridCacheonly when the named Redis connection string (defaultredis) is set (:225-228), since with no L2 the hybrid tier degrades to whatMemoryCacheServicealready provides (:208-214).AddScheduledJobs(DependencyInjection.Jobs.cs:37-55) andAddScheduledJob<TJob>(:72-78) wire the recurring-job feature (ADR-074). The first bindsSchedulerSettingswith validation (:39-42) and registersScheduledJobRunnerviaTryAddEnumerablerather thanAddHostedService(:44-48), so a host or two modules calling it twice cannot run two runners racing for the same rows. The second registers one job scoped, both as the concrete type and into the accumulatingIEnumerable<IScheduledJob>(:75-76); the doc spells out that the job is scoped because the runner resolves it in a fresh scope per execution and it must hold no state between runs (:66-70).AddAuditTrail(DependencyInjection.Jobs.cs:112-135) bindsAuditTrailSettings(:110-113), registers the trail interceptor as a singleton for the same statelessness reason as the other save interceptors (:115-117), the scoped reader (:119), and, notably,AddScheduledJob<AuditTrailCleanupJob>()(:124). Registering the retention job here rather than inAddScheduledJobskeeps the two features independent, and the remarks state the operational consequence plainly (:97-101): without the scheduler the trail still records every change and nothing is ever purged, soAuditTrail:RetentionDaysis inert.AddMultiTenancy(DependencyInjection.cs:347-367) bindsTenancySettingsand addsTenancySettingsValidatorthroughTryAddEnumerable(:363-364). What it switches on is resolution, not isolation: the filter, the interceptor andITenantContextare always present and inert until a tenant resolves (:325-329), and aTenancy:Tenants:{id}:DataSources:{sourceName}override naming a source that does not exist fails startup rather than silently falling back to the shared database (:339-344).- The five opt-in identity completions (ADR-116), in
DependencyInjection.Auth.cs.AddTwoFactorAuthentication(configuration)(DependencyInjection.Auth.cs:48-69) bindsTwoFactorSettingsand registersITwoFactorService/TotpTwoFactorServicesingleton, holding only the bound settings and the clock it judges a code's time step against, withTimeProvider.Systemadded throughTryAddSingletonbeside it so a host's own clock is never displaced (:55-58),ITwoFactorSecretProtector/DataProtectionTwoFactorSecretProtectorsingleton plusAddDataProtection(), so the shared secret reaches the app's store only in protected form and a multi-replica host needs the shared key ring (:60-63), andITwoFactorAuthenticator/TwoFactorAuthenticatorscoped (shares the request's unit of work,:65-66). It registers noITwoFactorStoredeliberately, because the account's secret and recovery hashes belong to the consumer's ownUseraggregate (:32-35). Calling it together with registering the app's store arms the sign-in challenge: provided the app registersAuthenticationValidatorsby type, the container builds it with the registered authenticator andAuthenticationServiceBaseuses it whenever its owntwoFactorargument is null, with no change to the app'sAuthenticationServiceconstructor; once called, the store is required, and a host that wants enrollment without the challenge overridesChallengeSecondFactorAsync(:37-44).AddEmailConfirmation(configuration)(DependencyInjection.Auth.cs:83-103) bindsEmailConfirmationSettingsand registersIEmailConfirmationTokenService/EmailConfirmationTokenServicescoped (:91),IAccountClaimService/AccountClaimServicescoped, the account-proof stepsConfirmEmailHandlerBaseruns for an account that holds a password, scoped like the refresh-session and two-factor stores it writes through, with the app'sITwoFactorStoreoptional (:93-96), plusTimeProvider.SystemthroughTryAddSingleton(:100), because the token service stamps expiries from the injected clock:AddServicesregisters the same clock (DependencyInjection.cs:416), and theTryAddkeeps this call self-sufficient without displacing a host's ownTimeProvider; an unconfirmed account is refused only onceRequireConfirmedEmailis set AND the app'sUserimplementsIEmailConfirmableUser(DependencyInjection.Auth.cs:78-81).AddSignInLinks(configuration)(DependencyInjection.Auth.cs:115-127) bindsSignInLinkSettingswith validation (:117-120) and registersISignInLinkTokenService/SignInLinkTokenServicescoped plusTimeProvider.SystemthroughTryAddSingleton(:123-124); it issues nothing on its own, since links are sent and redeemed only once the app wires the handler bases and a controller ANDAuthentication:SignInLinks:Enabledis set (:112-113).AddLegalAcceptance(configuration)(DependencyInjection.Auth.cs:148-157) bindsLegalAcceptanceOptionsfrom theLegalsection and nothing else: it registers noILegalAcceptanceService, because the accepted version and instant belong to the app's ownUseraggregate, so the consumer supplies that implementation plus a controller deriving fromLegalAcceptanceControllerBase. It deliberately omitsValidateOnStart, unlike its siblings, since the singleLegal:CurrentTermsVersionsetting has no invalid value (:150-152). The options reach registration throughAuthenticationValidatorsas an optional constructor argument, so with the setting unset the call changes nothing.AddStoredPermissionGrants(configuration)(DependencyInjection.Auth.cs:183-230) bindsPermissionGrantSettings(:185-188); registersPermissionGrantModelContributoras a singletonIModelContributorthroughTryAddEnumerable(:191-192), and that registration IS the opt-in: the contributor appliesApplyPermissionGrantConfigurationto the model of the one context whose physical source is named byAuthentication:PermissionGrants:DataSourceName, so no consumer calls that extension by hand and a host that never opts in keeps a byte-identical model (:175-180, ADR-148); the scopedEFPermissionGrantStore(:194); onePermissionGrantCachesingleton that answers as bothIPermissionGrantCacheandIPermissionGrantCacheInvalidator, so an edit and the reads that follow it cannot see two different snapshots (:196-202);PermissionRoleEditUnitscoped, matching the context factory it runs each edit's transaction on (:204-205), thenIRoleAdministrationService/StoredPermissionRoleAdministrationService(:206); and thePermissionGrantRefreshServicehosted service throughTryAddEnumerable, so two modules calling it never start two refresh loops (:208-211). It then decorates whateverIPermissionRegistryis registered withLayeredPermissionRegistryvia the framework's ownTryDecorateWith(ServiceCollectionDecoration,:216), so it belongs AFTERAddAuthorizationPolicies(); whenTryDecorateWithfinds nothing it registers a layered registry over an empty compiled one and offers that same empty instance asIPermissionCatalog, so the stored layer and the administration surface still work standalone (:213-227). AddServices(DependencyInjection.cs:373-423) registers the small services and encodes a subtle lifetime lesson:TokenServiceis a singleton (:393) with a seven-line comment explaining why (:386-392): a scoped lifetime disposed the RSA handle at end-of-request while IdentityModel's staticCryptoProviderCachestill held the cached signature provider wrapping it, throwingObjectDisposedExceptionon the next RS256 sign.[Rubric §11, Security](correct signing-key lifecycle). It also sets the defaultIEventBustoInProcessEventBus(:395) and the defaultIMessageBustoInProcessMessageBus(:401), registersITenantContextunconditionally with the reasoning inline (:379-383), registersTimeProvider.SystemandSmtpEmailSender(:403-404), and wires the inert no-op defaults for push and the live channel (:405-406), native push (ADR-044,NullNativePushSenderandNullPushDeviceRegistrar,:408-413) and file storage (ADR-045,NullFileStorageService,:415-420). The comments name the vendor adapter calls that swap those defaults (Azure, AWS and GCP packages) and state that image normalization is the application's own concern, because decoding needs a native image library every consumer would otherwise carry (:415-419).AddPushNotifications(DependencyInjection.Notifications.cs:62-110) binds the settings (:40-43), adds SignalR (:45), adds the Redis backplane only when aredisconnection string exists (:47-59) withChannelPrefixset to the resolvedApplicationNamespace(:56-58), because the channel derives from a hub type every consumer shares, so without it one application's pushes reached another's clients (SEC-Common-53,:50-55). It appends the SignalR senders over the null defaults (:62-63) andReplaces SignalR'sDefaultUserIdProviderwithClaimBasedUserIdProvider(:67), since aTryAddthere never took effect and a principal carrying only the rawsubclaim got a nullUserIdentifier(:64-66).AddBrokerMessaging(DependencyInjection.Messaging.cs:63-176) is the extraction pivot. It readsMessageBusSettings, falling back tonew MessageBusSettings()when the section is absent (:69-70); onInProcessit returns immediately (:72-75), leaving the in-process bus in place; otherwise it re-runs the outbox guard (:80, with the comment at:77-79: a service host that wires the broker without the full infrastructure registration must still fail loudly) and resolves theIBrokerTransportbefore anything is registered, so an unregistered provider fails without leaving a half-registered broker behind (:82-84). It then requiresApplication:Namespace(:86-89, SEC-Common-53): every topic is prefixed with the resolvedApplicationNamespace, so two applications on one broker never publish onto each other's topics, and the value must be explicit because the fallback (the host's own application name) differs per service, which would put publishers and consumers on different topics. The host's consumer callback runs against aBrokerConsumerBuilder(:90-92), where each service callsRegisterIntegrationEventConsumer<TEvent>()(orRegisterUpcastedIntegrationEventConsumer<TEvent>()for a retired contract) per event it handles (:54-57), and the result becomes oneBrokerTopologysingleton: one queue (MessageBus:QueueNameor the application name) with one subscription per consumed event (:94-99, described at:41-46). It registers one scoped consumer per subscription, resolved by the receive pipeline from a fresh scope per attempt (:101-106), and the singletonIBrokerReceivePipelineasBrokerReceivePipeline, handed the transport'sMaxRedeliveryDelay(:108) and the inbox's dedup horizon fromInboxPosture, read from configuration like theMessageBussection so a host that wires the broker withoutAddInfrastructurestill honours it, with no horizon when the inbox is off (:110-116), registered at:117-124. It thenReplaces the scopedIMessageBuswithBrokerMessageBus(:128) andIEventBuswithBrokerEventBus(:134), the deliberate exception to theTryAddrule, because the in-process bus must not run alongside the broker (ADR-066, ADR-118). Last, after the inbox branch below, it callstransport.Registerwith aBrokerTransportContextcarrying the settings, the resolved connection string, the configuration and the topology (:165-173), so the transport sees every framework registration and adds only itsIBrokerPublisherand its hosted receiver (:41-46), and a transport configuration error throws at startup.PostgreSqlBrokerTransportregisters its schema migrator inside thatRegistercall, ahead of its receiver, because hosted services start in registration order (Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:75-79).- The inbox branch (
DependencyInjection.Messaging.cs:141-163) chooses the consumer-side dedup store fromsettings.IsInboxEnabled, the resolved posture rather than the raw flag (unset means ON for a broker,:136-140):EfInboxStorescoped when on (:143), beside the scopedIInboxRecorder/EfInboxRecorder, the atomic half of the per-handler inbox thatScopedIntegrationEventHandlerBaseresolves per delivery so the handler's own save commits its row, left unregistered when the inbox is off so the base stages nothing (:145-149, ADR-021), withTimeProvider.SystemTryAdded for the store'sProcessedOnstamp (:153); and when off the singletonNoOpInboxStore(:157) plus anInboxDisabledWarningServicehosted service (:162). That second registration is the whole point of the branch: a disabled dedup store looks exactly like an enabled one until a duplicate side effect reaches a customer, so the posture costs one startup Warning to make visible (:159-161). AddBrokerTransport(DependencyInjection.Messaging.cs:189-201) is how an adapter package (or a host with a transport of its own) makes a provider name selectable: it rejects an emptyName(:178-181) and adds the instance throughTryAddEnumerable(:183), so registering the same adapter twice is harmless, and when two transports share a name the last one registered wins. It must run BEFOREAddBrokerMessaging, which picks the transport while registering the broker services (:163-170).- The four private helpers (
DependencyInjection.Messaging.cs:204-317) sit outside the extension block.ResolveBrokerTransport(:199-232) returns the built-inRabbitMqBrokerTransportorPostgreSqlBrokerTransportfor those names (:201-209), else the LAST adapter transport registered under the name, read straight off the collection because no provider exists yet (:211-221); with no match it throws naming the adapter package and its registration call whenMessageBusProvidersknows one, and the available providers (:223-231).EnsureOutboxAvailableForProvider(:248-255) throws when a broker transport is paired with an explicitly disabled outbox, and the message says why in operational terms: the outbox is the only publish path a broker deployment has, so the alternative is every cross-service event vanishing while the service looks healthy.EnsureApplicationNamespaceConfigured(:270-281) throws whenApplication:Namespaceis missing or blank, and its message carries the fix (the same value on every service, with anappsettings.jsonand an environment-variable example).ResolveBrokerConnectionString(:293-302) applies an explicit precedence:MessageBus:ConnectionString, thenConnectionStrings:rabbitmq(what Aspire injects), thenConnectionStrings:messaging; without that fallback a transport would keep its own default host (RabbitMQ'slocalhost:5672) and never reach the Aspire-allocated container port (:283-292). - Retry, redelivery and dead-lettering live in one receive pipeline; the transports only apply its verdict.
[Rubric §29, Resilience & Business Continuity]:BrokerReceivePipeline.ProcessAsync(Messaging/Consumers/BrokerReceivePipeline.cs:82) dead-letters a message that cannot be read as its event type without retrying it (:115-144), runs the consumer up toRetryLimit+ 1 times, each attempt in a fresh scope, waitingBrokerTransportPolicies.RetryDelaybetween attempts (BrokerReceivePipeline.cs:180-197,Messaging/Transports/BrokerTransportPolicies.cs:29), then returns aRedeliverdisposition on the next second-level interval (BrokerReceivePipeline.cs:165-166), the intervals coming fromBuildRedeliveryIntervalsclamped to the transport'sMaxRedeliveryDelay(BrokerReceivePipeline.cs:72,BrokerTransportPolicies.cs:67), and aDeadLetteronce they are spent (BrokerReceivePipeline.cs:170-176). Backpressure is the one policy each transport applies itself, readingMessageBusSettings.PrefetchCount(Messaging/MessageBusSettings.cs:223) andConcurrentMessageLimit(:233) directly, with no shared policy inBrokerTransportPolicies(BrokerTransportPolicies.cs:7-9); RabbitMQ defaults the concurrency to the processor count and the prefetch to twice the concurrency (Messaging/Transports/RabbitMq/RabbitMqBrokerTransport.cs:95,:104-105). The Azure Service Bus transport lives in theMMCA.Common.Azureadapter package (MMCA.Common/Source/Hosting/MMCA.Common.Azure/Messaging/AzureServiceBusTransport.cs:37) and Amazon SQS inMMCA.Common.Aws(MMCA.Common/Source/Hosting/MMCA.Common.Aws/Messaging/AmazonSqsTransport.cs:40), the one transport with a redelivery cap (15 minutes,:65). AddNpgsqlDataSourceConfigurator(DependencyInjection.Persistence.cs:24-37) registers anINpgsqlDataSourceConfiguratorthroughTryAddEnumerable(:28) and a keyedNpgsqlDataSourcesingleton per distinct connection string (:32-34), so the PostgreSQL contexts and the readiness check share one data source; adapter packages call it from their own registration method (for exampleAddAwsRdsIamAuthentication), and it is order-independent relative toAddInfrastructure(:12-20).
Why it's built this way: the
extension(IServiceCollection)syntax keeps every Infrastructure registration on one type without a proliferation of static helper classes (ADR-106), and pushing all concrete choices into one composition root at the layer edge is what keeps Application and Domain free of framework references (ADR-006 for the database-per-service wiring, ADR-007/ADR-008 for the broker/extraction path). Vendor-specific transports, push senders and storage are registered by the adapter packages against the extension points here (AddBrokerTransport,AddNpgsqlDataSourceConfigurator, theNull*defaults), which keeps the core free of any cloud SDK (ADR-134). See the DI-sequence note inMMCA.Common/AGENTS.md: hosts callAddApplicationDecorators()last so the decorators (applied throughServiceCollectionDecoration) wrap handlers already registered, but the relative position ofAddInfrastructureis not otherwise ordering-sensitive, andAddCommonHybridCacheis explicitly documented as order-independent in both directions (DependencyInjection.Caching.cs:174-180).Where it's used: called from each service host's
Program.cs(the reference apps and the extractedMMCA.ADC.*service hosts) afterAddApplication(); the optional methods (AddScheduledJobs,AddAuditTrail,AddMultiTenancy,AddCommonHybridCacheorAddCommonHybridCacheWhenRedisConfigured,AddBrokerMessaging,AddPushNotifications, the identity completions) are added by the specific hosts that need those capabilities.AddScheduledJobsTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/AddScheduledJobsTests.cs:15) pins the double-registration behavior of the scheduler pair.Caveats / not-in-source: the exact set of consuming
Program.csfiles is in the downstream apps (MMCA.ADC / MMCA.Store / MMCA.Helpdesk), not in this repository, so the precise call sites are Not determinable from source here.
BrokerMetrics
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMetrics.cs:18· Level 0 · class (internal, static)
What it is: the OpenTelemetry instrument set for the broker transport (
BrokerMetrics.cs:5-11). One meter carrying four instruments: integration events dead-lettered after every retry and redelivery failed, settles that failed after the pipeline had decided, the dead-letter depth of a queue, and outbox publishes the circuit breaker refused to even attempt (BrokerMetrics.cs:30-67).Depends on:
System.Diagnostics.Metrics(BCL) only (BrokerMetrics.cs:1). Nothing first-party. It is the exact same shape asSchedulerMetrics, for a different feature.Concept: the one-meter-per-feature instrument holder, taught under
SchedulerMetrics. What is worth teaching here is which numbers were chosen.[Rubric §13, Observability & Operability]assesses whether a running system can be understood from outside: broker delivery is asynchronous and out of band, so a consumer that keeps failing produces no failed HTTP response anywhere, and the only evidence is a message quietly landing in the dead-letter location.broker.fault.countis therefore the natural alert target for consumer health (BrokerMetrics.cs:25-29).broker.settle.failure.countcovers the step after the decision: an ack, delete, redelivery or dead-letter write that did not go through is offered again afterBrokerTransportPolicies.SettleFailureBackoff, so a steady rate means the transport cannot settle at all (a permission or dead-letter location problem) and the same messages keep coming back (BrokerMetrics.cs:35-41).broker.dead_letter.depthturns the fault count into a backlog: a depth that keeps rising is events nobody has triaged (BrokerMetrics.cs:47-51). The circuit counter exists because the class doc insists on a distinction an operator would otherwise have to infer: a publish rejected by an open circuit never reached the broker at all (BrokerMetrics.cs:57-63), which is different from a publish that reached it and failed.[Rubric §29, Resilience & Business Continuity]: those rejected rows stay leased and are retried on a later cycle, so the counter measures fail-fast behavior working as designed rather than data loss.Walkthrough:
MeterName = "MMCA.Common.Broker"(BrokerMetrics.cs:21) and the single staticMeterbuilt from it (:23). The doc carries the same never-create-a-second-meter warning as the scheduler (BrokerMetrics.cs:13-15), with the failure mode spelled out: a duplicate instance publishes a parallel set of instruments under one name, and a listener enabling one silently misses the measurements recorded on the other.FaultCounter(BrokerMetrics.cs:30-33),broker.fault.count, unitmessages, tagged byevent_typeandqueue.SettleFailureCounter(BrokerMetrics.cs:42-45),broker.settle.failure.count, unitmessages, tagged bytransportandqueue.DeadLetterDepthGauge(BrokerMetrics.cs:52-55),broker.dead_letter.depth, aGauge<long>rather than a counter, unitmessages, tagged bytransportandqueue. It is recorded once per retention sweep, and only by a transport that keeps its own dead-letter store (the PostgreSQL transport'sdead_letterstable) (:47-51).CircuitOpenCounter(BrokerMetrics.cs:64-67),broker.circuit.open.count, same unit, tagged byevent_typeonly.
Why it's built this way:
internal static readonlyinstruments created once at type initialization means the recording sites resolve nothing from DI. The meter name is duplicated as a literal in MMCA.Common.Aspire (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:67) because that package has no reference to Infrastructure, and the doc records that duplication rather than letting the next reader discover it (BrokerMetrics.cs:8-11). The instruments only move in a host that runs a broker transport, since the in-process bus has no receive pipeline and no broker publish path.Where it's used:
BrokerReceivePipelineadds toFaultCounterinAfterRetriesExhausted, once the last second-level redelivery is spent, right after its one Error log, tagging the event type and the host's queue name (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:195-199).PostgreSqlReceiveradds to the same counter when a row reaches its delivery limit before any consumer decided on it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiver.cs:280-288), and adds toSettleFailureCounterwhen a settle throws, before backing the message off (PostgreSqlReceiver.cs:270-275);RabbitMqReceiverdoes the same with thetransporttagrabbitmq(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqReceiver.cs:227-231).PostgreSqlDeadLetterCleanupServicerecordsDeadLetterDepthGaugeafter each purge with the queue's remaining count (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlDeadLetterCleanupService.cs:77-81).OutboxProcessoradds toCircuitOpenCounteron its publish path (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:783), where an earlier comment notes that the per-row signal stays on the metric while the log line is per cycle (OutboxProcessor.cs:654).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
SmtpSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Mail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Mail/SmtpSettings.cs:9· Level 0 · class (sealed)
What it is: the
Smtpsection: host, port, credentials, TLS toggle, and the default sender and recipient addresses. Validated by data annotations at startup (SmtpSettings.cs:5-8).Depends on:
System.ComponentModel.DataAnnotationsfor[Range](SmtpSettings.cs:1). Consumed by SmtpEmailSender, the IEmailSender implementation.Concept: the validate-on-start gate taught under ConnectionStringSettings, here guarding a numeric range rather than a cross-section rule.
[Rubric §15, Best Practices & Code Quality]assesses whether avoidable failures are moved earlier:[Range(1, 65535)]onPort(SmtpSettings.cs:21) means a configuration typo such as0or70000fails the host at boot with a named error instead of surfacing as a socket exception the first time the application sends mail. Note also the named constant instead of a magic number:DefaultSmtpPort = 25is apublic static readonlyfield (:15) used as the property's own default (:22), so the value is discoverable and testable rather than inlined.[Rubric §11, Security]:Passwordis a plainstring(:28), so it is only ever as safe as the configuration provider that supplies it (user-secrets or Key Vault, never a committedappsettings.json).Walkthrough: two static fields then eight
{ get; init; }members.SectionName = "Smtp"(SmtpSettings.cs:12) andDefaultSmtpPort = 25(:15).Host(:18),Port(:22),Username(:25),Password(:28),EnableSsl(:31, defaulting tofalse),From(:34),To(:37),TimeoutSeconds(:53,[Range(1, 600)], default30). Every string defaults tostring.Empty, so an absent section binds cleanly; onlyPortandTimeoutSecondsare range-checked.Tois documented as the default recipient used by the no-argumentSendAsyncoverload (:36-37).EnableSslno longer defaults to "off" when the key is unset: SmtpTransportSecurity resolves the effective value, turning TLS on outside Development (SEC-Common-54); the property itself still carries a plainfalsedefault because it only records what the host configured, not the resolved posture (:16-24).TimeoutSecondsexists because the .NET default of 100 seconds outlives most callers' own budget: a relay that accepts the TCP connection and then stops answering parks the request thread for the full 100s, and a notification burst parks one per message; 30 seconds keeps a stalled relay inside the caller's timeout instead of outliving it (:41-49).- The consumer is deliberately plain: SmtpEmailSender takes
IOptions<SmtpSettings>in its primary constructor and snapshots.Valueinto a readonly field (SmtpEmailSender.cs:12-14), then builds a freshSmtpClientper send fromHost/Portplus aNetworkCredentialand the resolved TLS decision (:25-29), and aMailMessagefromFrom(:32-35).
Why it's built this way: annotations plus
ValidateOnStartcost one line at registration and move an entire class of misconfiguration from run time to boot, the contract ADR-070 describes. Resolving TLS through SmtpTransportSecurity instead of a hard-coded default keeps the failure mode fail-closed outside Development (ADR-122).Where it's used: bound with
.ValidateDataAnnotations().ValidateOnStart()inAddInfrastructure(DependencyInjection.cs:81-84); read by SmtpEmailSender.
ExceptionChain
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Diagnostics·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Diagnostics/ExceptionChain.cs:25· Level 0 · class (internal, static)
What it is: a one-line renderer for an exception and its causes, used for a background job's
LastErrorcolumn, its log text and its span status (ExceptionChain.cs:5-8).Depends on: BCL only (
StringBuilderfromSystem.Text,Stack<T>,AggregateException) (ExceptionChain.cs:1).Concept introduced: record the cause, not the wrapper.
[Rubric §13, Observability & Operability]assesses whether a failure can be diagnosed from what the system recorded. Wrapper exceptions hide the cause:SmtpExceptionsays only "Failure sending mail." while the server's reply sits onInnerException, and recording the outer message alone left 21 dead-lettered attempts in Store production (2026-11-01) with nothing to diagnose (ExceptionChain.cs:11-14). The answer is to walk the chain, not to store stack traces: the column and the span status are read by people, and the processors that need a stack log the exception object itself (:20-22).Walkthrough:
MaxLevels = 8(ExceptionChain.cs:28): the most levels, the outer exception included, one description renders.Separatoris" ---> "(:30).Describe(exception)(ExceptionChain.cs:35-63) starts with the outer message, then walks the causes depth first through an explicit stack (:45-46) until it is empty orMaxLevelsis reached (:48). Each cause is appended as" ---> {Type}: {Message}", except one repeating the previous message, which adds nothing and is skipped (:53-57). An exception with no cause renders as its bare message.PushCauses(ExceptionChain.cs:65-78) pushes every inner exception of anAggregateExceptionin reverse, so the first one is rendered first (:67-73), and otherwise the singleInnerException(:74-77).
Why it's built this way: an explicit stack rather than recursion keeps the walk ordered for aggregates nested inside aggregates, and the level cap keeps one pathological chain from flooding a column; callers still fit the result to their column width (
ExceptionChain.cs:17-22).Where it's used:
OutboxProcessorfor a failed row's error (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:761),InternalCommandProcessorfor a command that threw (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:487), andScheduledJobRunnerfor a failed job run (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobRunner.cs:753). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Diagnostics/ExceptionChainTests.cs.
TransportFailure
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Diagnostics·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Diagnostics/TransportFailure.cs:17· Level 0 · class (internal, static)
What it is: the one classification of a cloud SDK call that failed before the service answered, shared by the cloud adapter packages (MMCA.Common.Aws, MMCA.Common.Azure, MMCA.Common.Gcp) so every adapter maps the same exception to the same outcome (
TransportFailure.cs:3-7).Depends on: BCL only:
HttpRequestException,IOException,TimeoutException,OperationCanceledExceptionandCancellationToken(TransportFailure.cs:23-25). Nothing first-party.Concept introduced: a transport failure is not the caller's cancellation.
[Rubric §29, Resilience & Business Continuity]assesses whether a dependency outage degrades into a handled failure instead of an unhandled exception. A connect or DNS failure, a dropped connection, or a timeout after the client's own retries escapes the cloud SDKs unwrapped, so an adapter that only caught the vendor's service exception would let a network blip crash the request; this type tells the adapter to handle those like a service failure (a failedResult, a counted push failure) (TransportFailure.cs:9-12). The other half of the rule is what keeps it honest: once the caller's token is cancelled, nothing is a transport failure, whatever the aborted call threw, so a cancelled request propagates on every adapter instead of turning into a failed result on some of them (:12-15). The subtle case isOperationCanceledException: one the caller did not request (an SDK client timeout surfaces this way) is transient, one the caller did request is not, and only the token can tell them apart.[Rubric §15, Best Practices & Code Quality]: one predicate in the package every adapter already references, rather than three hand-copied exception lists that drift one type at a time.Walkthrough:
IsTransient(exception, cancellationToken)(TransportFailure.cs:23-25):falseas soon ascancellationToken.IsCancellationRequested(:24); otherwisetruewhen the exception is anHttpRequestException,IOException,TimeoutExceptionorOperationCanceledException(:25). Theis ... or ...type pattern matches derived types too, so any subclass of those four (for exampleTaskCanceledException, anOperationCanceledException) also counts.
Why it's built this way: the type is
internaland reaches the adapters throughInternalsVisibleToforMMCA.Common.Aws,MMCA.Common.AzureandMMCA.Common.Gcp(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:43-45), so the shared rule is not public API a consumer could start depending on. Returning aboolfor use in an exception filter (catch ... when) means a non-matching exception is never caught at all, so its stack and the caller's cancellation flow through untouched.Where it's used: as the exception filter on the storage adapters, which log the exception and return a failed
Resultbuilt fromError.Unavailable:AzureBlobFileStorageService(MMCA.Common/Source/Hosting/MMCA.Common.Azure/Storage/AzureBlobFileStorageService.cs:65-71,:92),S3FileStorageService(MMCA.Common/Source/Hosting/MMCA.Common.Aws/Storage/S3FileStorageService.cs:88,:118) andGcsFileStorageService(MMCA.Common/Source/Hosting/MMCA.Common.Gcp/Storage/GcsFileStorageService.cs:77,:109).SnsPushDeviceRegistrarORs it withAmazonServiceException, so a service error and a transport error take the same failed-Resultpath (MMCA.Common/Source/Hosting/MMCA.Common.Aws/Notifications/SnsPushDeviceRegistrar.cs:72-79,:112,:147,:270). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Diagnostics/TransportFailureTests.cs, whose theory data runs an HTTP, IO, timeout, client-timeout and unrequested-cancellation failure (TransportFailureTests.cs:13) both before and after the caller cancels (:26,:31), plus any other exception (:41).
MessageBusSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:13· Level 1 · class (sealed)
What it is: the
MessageBussection. It selects the transport, says how to reach the broker, which queue this host receives on and whether the transport may create its own broker entities, how hard to retry a failing consumer, how much work to take on at once, and whether the two store-and-forward guards (the transactional outbox and the consumer-side idempotency inbox) are on (MessageBusSettings.cs:6-12). Despite the name it is the single switch for the whole event delivery posture, not just for the wire protocol.Depends on: MessageBusProviders, the string constants and case-insensitive predicates for the built-in transport names (
MessageBusSettings.cs:2), and, in its XML doc only, IBrokerTransport (whoseMaxRedeliveryDelayit names,:188-195). Externals:System.ComponentModel.DataAnnotationsfor the[StringLength]and[Range]guards (:1).Concept introduced: a tri-state flag that resolves from the transport. Two of the properties here are
bool?, notbool, and each has a computed companion.EnableInbox(:138) is the raw configured value andIsInboxEnabled(:148) is what every framework component actually reads:!MessageBusProviders.IsInProcess(Provider) && (EnableInbox ?? true).EnableOutbox(:178) andIsOutboxEnabled(:186) resolve asEnableOutbox ?? !MessageBusProviders.IsInProcess(Provider). The point of the third state is that "the host said nothing" and "the host said false" are different facts. Unset means "let the transport decide", which turns both features ON for a broker and OFF in-process. An explicit value is honored only where it can mean something, and the two flags differ on which side that is. The inbox override counts only on a broker transport: in-process no inbox is ever wired (the store and recorder are registered only byAddBrokerMessaging), so even an explicittrueresolves to off rather than letting a reader believe a dedup store exists (:128-135,:140-147). The outbox override counts in-process in both directions, while turning it off under a broker is refused (described underEnableOutbox). That is why a settings class that could have been a bag of booleans carries derived properties: the resolution rule lives once, next to the data, so the republish guard, the inbox purge, the receive pipeline's horizon check and the broker registration all agree on whether an inbox exists (:145-147).[Rubric §6, CQRS and Event-Driven]assesses how reliably a state change turns into a delivered event. Both resolved flags default ON for a broker deliberately, and the XML doc argues the case rather than just stating it: broker delivery is at-least-once by contract, so an ack after a network blip, a redelivery after a lease expiry, or an outbox row republished after a crash all hand the same event to the same handlers twice, and with the inbox off every one of those becomes a duplicate side effect (:116-125, ADR-021). Symmetrically, a single-process host dispatches every event inside the process that raised it, so the store-and-forward hop buys it two background services, a table and a poll loop for nothing (:157-162, ADR-100).[Rubric §29, Resilience and Business Continuity]assesses whether transient failures are absorbed before they become lost messages. This class configures two independent retry tiers, both run by the framework's own receive pipeline rather than by a broker library, so every transport behaves the same.RetryLimit/RetryMinIntervalSeconds/RetryMaxIntervalSecondsdrive the in-process tier: BrokerReceivePipeline runs the consumer up toRetryLimit + 1times, each attempt in a fresh DI scope (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:204-222), waiting the exponential delay BrokerTransportPolicies.RetryDelaycomputes from the floor and the cap (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/BrokerTransportPolicies.cs:38-44).RedeliveryIntervalsSecondsdrives the second tier: once the in-process attempts are spent, the pipeline schedules the next redelivery on the host's queue while one is left, and dead-letters only after the last (BrokerReceivePipeline.cs:177-200).[Rubric §7, Microservices Readiness]assesses whether several services can share infrastructure without colliding. Each host receives on ONE queue of its own, derived from its application name, and every event it consumes is bound to that queue, so two services consuming the same event each get their own copy instead of competing for one (:56-62). Topic names are separately prefixed with ApplicationNamespace, which a broker host must set.Walkthrough: two static members, thirteen
initproperties, and two computed properties.SectionName = "MessageBus"(MessageBusSettings.cs:16), the bind key.Provider(:25): astring, not an enum, compared case-insensitively, defaulting toMessageBusProviders.InProcess, so the modular monolith is the zero-configuration case.InProcess,RabbitMqandPostgreSqlare built in; any other value names an IBrokerTransport an adapter package registers beforeAddBrokerMessaging(for exampleAzureServiceBusfromMMCA.Common.AzurethroughAddAzureServiceBusTransport()) (:18-24). When nothing is registered under the name,AddBrokerMessagingfails namingAddBrokerTransport(...)as the fix (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:243). The transport-selection decision is ADR-066, and the move of vendor brokers into adapter packages is ADR-134.ConnectionString(:33): nullable, and only the first of three sources.ResolveBrokerConnectionStringprefers it, then falls back toConnectionStrings:rabbitmqandConnectionStrings:messaging, which is what Aspire injects viaWithReference(broker)(DependencyInjection.Messaging.cs:302-316).EmulatorAdminEndpoint(:54) with[StringLength(2048)](:53): the base address of the Azure Service Bus emulator's HTTP management plane. The emulator serves the data plane (AMQP) and the management plane (HTTP) on two different ports, so the administration client that provisions topics, subscriptions and queues cannot be derived fromConnectionStringalone (:41-45). It is read only when the connection string carriesUseDevelopmentEmulator=true, and then a missing or malformed value fails at registration (:47-51). The reader is the Azure adapter, not this assembly: AzureServiceBusTransport hands it to ServiceBusEmulatorSupport.QueueName(:71) with[StringLength(50)](:70): the ONE queue this host receives on, ornull(the default) to derive it from the host application name in lower kebab case with a trailing-serviceremoved, soMMCA.ADC.Engagement.Servicereceives onmmca-adc-engagement(:56-62).AddBrokerMessaginghands it with the host'sapplicationNameto BrokerNaming.Queue(DependencyInjection.Messaging.cs:96). Set it explicitly only to pin a name that must survive a host rename; replicas share the queue as competing consumers anyway, because they run under the same application name (:63-68).ProvisionTopology(:84), defaulttrue: whether the transport creates the topic per event, this host's queue and the topic-to-queue bindings, idempotently, when the receiver starts and on the first publish to a missing topic (:73-77). Set itfalsewhere the entities are provisioned out of band (infrastructure as code, or an identity that may send and receive but not manage), and the transport then assumes every entity exists (:78-82).RetryLimit(:94) with[Range(0, 20)](:93), default5: a message is attempted up toRetryLimit + 1times per delivery, and0disables in-process retries (:86-92).RetryMinIntervalSeconds(:101) with[Range(0, 300)], default1, andRetryMaxIntervalSeconds(:107) with[Range(0, 3600)], default30: the floor and the cap of the doubling backoff.EnableInbox(:138) andIsInboxEnabled(:148). On a broker transport an explicit value wins in both directions; onInProcessthe setting is ignored and the resolved value is alwaysfalse(:128-135).AddBrokerMessagingregisters EfInboxStore when the resolved value is true and NoOpInboxStore plus a startup InboxDisabledWarningService when it is false, so an opt-out is recorded in the log rather than passing silently (DependencyInjection.Messaging.cs:141-143,:157-162). That branch only runs for a broker transport, because the in-process provider has already returned (:72,:136-140). TheInboxMessagestable is part of the shared relational model created by the standard migrations (Cosmos hosts skip it), so turning it on for a migrated relational host needs no schema work (:112-115).EnableOutbox(:178) andIsOutboxEnabled(:186).AddInfrastructurereads the resolved value to decide whether to run OutboxProcessor and OutboxCleanupService or the single OutboxDisabledNoticeService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:298-306). Turning it off under a broker is not honored:EnsureOutboxAvailableForProviderthrows at registration, because a broker with no outbox has no delivery channel at all (DependencyInjection.Messaging.cs:263-265, argued atMessageBusSettings.cs:165-170), andAddBrokerMessagingruns that check itself (DependencyInjection.Messaging.cs:80) so a service host that wires only the broker still fails loudly. TheOutboxMessagestable stays part of the EF model either way, so flipping the flag is never a migration. With the outbox off, a handler failure is logged at Error and nothing retries it; each event dispatches on its own, so one failing handler does not stop the later events of the save (MessageBusSettings.cs:173-175).DefaultRedeliveryIntervalsSeconds(:196), a static[60, 600, 3600]: one minute, ten minutes and one hour, a spread wide enough to ride out a dependency restart, a failover and a short incident without an operator replaying the dead-letter queue by hand (:188-195).RedeliveryIntervalsSeconds(:219): nullable with no initializer, and that is on purpose: the configuration binder appends a configured list to an existing collection instead of replacing it, so a non-null default would make the defaults impossible to shorten by configuration (:209-211). A configured list REPLACES the default and is never merged with it; non-positive entries are dropped, so[0]turns second-level redelivery off (an empty array cannot be expressed in configuration); an interval longer than the transport'sMaxRedeliveryDelayis shortened to it, which matters on Amazon SQS with its 15 minute cap (:203-207).BuildRedeliveryIntervalsapplies all three rules (BrokerTransportPolicies.cs:76-82), andAddBrokerMessagingpasses the transport'sMaxRedeliveryDelayinto the pipeline that calls it (DependencyInjection.Messaging.cs:108,:117-124). Every transport honors the result: RabbitMQ through per-interval delay queues (no broker plugin), PostgreSQL through the row's visibility time, Azure Service Bus and Amazon SQS through their native scheduling (MessageBusSettings.cs:214-216).PrefetchCount(:229) andConcurrentMessageLimit(:239): both nullableint, both unset by default (the transport's own default then applies), and both carry[Range(1, int.MaxValue)](:228,:238), so a value below1fails the host at start through theValidateOnStartbinding inAddInfrastructure(:221-227,:231-237). No policy function sits between them and the transport: each transport reads the two values directly, because an invalid one has already failed startup (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/BrokerTransportPolicies.cs:7-9). RabbitMQ falls back to the processor count for concurrency and twice that for the prefetch window (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqBrokerTransport.cs:107-108,:117-118); PostgreSQL clamps its claim batch to the concurrency (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiverOptions.cs:52-53).PrefetchCountcaps how many messages the transport holds locally ahead of the consumer; a window larger than the work a consumer can finish inside its lock or lease is what turns a slow consumer into redeliveries, while a window of one serializes the queue (:223-225).ConcurrentMessageLimitcaps how many messages are consumed at once from the host's queue, the backpressure knob for how many database connections and downstream calls a burst of events can open (:233-236).
Why it's built this way: resolving both guards from the transport rather than shipping fixed defaults is what lets one settings class serve the monolith and the extracted-service topology at the same time (ADR-008), while keeping the at-least-once contract intact where it matters (ADR-003, ADR-021). Refusing an outbox-less broker at registration rather than honoring it follows the fail-fast configuration contract (ADR-070): the misconfiguration becomes a startup exception instead of silently dropped events. Keeping the retry, redelivery and backpressure knobs here, applied once by the framework pipeline, is what lets a new transport inherit the whole failure policy instead of re-implementing it.
Where it's used: bound with
.ValidateDataAnnotations().ValidateOnStart()inAddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:247-250), then read eagerly in the same method to runEnsureOutboxAvailableForProviderand gate the outbox hosted services (:294-298). The same method resolves the bound instance into the InboxPosture singleton, so the cleanup sweep and the republish guard read one inbox rule (:167-171).AddBrokerMessagingreads it again, falling back tonew MessageBusSettings()when the section is absent (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:70), short-circuits on the in-process provider (:72), and otherwise builds the BrokerTopology (:94-97), registers the receive pipeline with these settings and the inbox horizon anInboxPosturederives from them (:113-124), and replaces IMessageBus with BrokerMessageBus (:128) and IEventBus with BrokerEventBus (:134), so OutboxProcessor becomes the only delivery channel. InProcessEventBus reads the resolved outbox flag (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:62), and OutboxCleanupService purges inbox rows only whenIsInboxEnabledis true, reading it through the injectedInboxPosture(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxPosture.cs:23). The vendor receivers (AzureServiceBusTransport, AmazonSqsTransport) read the same instance (for exampleMMCA.Common/Source/Hosting/MMCA.Common.Aws/Messaging/AmazonSqsReceiver.cs). StartupConfigurationSummaryService logs the resolvedProviderandProvisionTopologyat start. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Settings/MessageBusSettingsTests.csandMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/BrokerTransportPoliciesTests.cs.Caveats: no broker library sits underneath any of these settings: MassTransit is banned from the framework (ADR-118, enforced by
MassTransit_MustNotBeReferencedinMMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Governance/DependencyVersionTestsBase.cs:13and the banned-assembly list inMMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Layering/ArchitectureRules.Transport.cs:16) and the transports are framework code, so every knob here is honored by MMCA.Common's own receive pipeline and transports rather than translated into a library's API.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
SmtpTransportSecurity
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Mail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Mail/SmtpTransportSecurity.cs:26· Level 1 · class (static, partial)
What it is: the resolver behind SmtpSettings
.EnableSsl. It answers whether an SMTP session must negotiate TLS, treating an unsetSmtp:EnableSslkey as "secure unless the host is Development" rather than as "off" (SEC-Common-54).Depends on:
IConfiguration,IHostEnvironment,ILogger, and SmtpSettings (the second overload's parameter).[LoggerMessage]source generation for the warning.Concept: fail-closed configuration for a security-relevant default.
[Rubric §11, Security]and[Rubric §22, Compliance & Governance]: leavingSmtp:EnableSslunset used to mean cleartext, becauseSmtpSettings.EnableSslis a plainbooldefaulting tofalse. This type reads the raw configuration key rather than the bound settings object, because the settings object cannot distinguish "configured false" from "never configured" once binding has happened (SmtpTransportSecurity.cs:39-40); only the presence of the key in configuration can. Development is the one carved-out exception, consistent with the workspace's dev-only-relaxations-fail-closed policy (ADR-122).Walkthrough: two overloads of
Resolveand one generated log method.Resolve(configuration, environment)(:37-49): readsSmtp:EnableSsl(EnableSslConfigKey = "Smtp:EnableSsl",:29); if it parses as a bool, that value wins; otherwise returnsenvironment?.IsDevelopment() != true, so a null environment is also treated as non-Development (secure by default).Resolve(settings, configuration, environment, logger)(:65-84): calls the first overload, and when the resolved value isfalse, the host is not Development,settings.Hostis set, and a logger was supplied, emits oneLogCleartextSmtpwarning naming the config key and the SMTP host before returning the same resolved value.LogCleartextSmtp(:686-690):[LoggerMessage(EventId = 5401, Level = Warning)], message text states plainly that credentials and message bodies, "password-reset tokens included," travel in cleartext to the named host.
Why it's built this way: a security-relevant default that only reveals itself the first time someone inspects network traffic is exactly the failure mode ADR-122 exists to close off; resolving from the raw configuration key rather than the bound
boolis what lets "unset" and "explicitly false" resolve differently at all.Where it's used: SmtpSettings
.EnableSsl's XML doc references it as the resolver of record (SmtpSettings.cs:29); called from SmtpEmailSender to decide theSmtpClient's TLS posture, and fromSensitiveDataLoggingGatefor the analogous decision on a different setting. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Mail/SmtpTransportSecurityTests.cs.
BrokerWire
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerWire.cs:12· Level 3 · class (internal, static)
What it is: the handful of wire-format facts the publish side (
BrokerMessageBus) and the receive side (BrokerReceivePipeline) must agree on: the JSON options the message body is written and read with, and the trace source both hops report on (BrokerWire.cs:7-11).Depends on:
OutboxMessage, whose internalSerializerOptionsinstance it reuses (BrokerWire.cs:3,:33). Externals:System.Diagnostics.ActivitySourceandSystem.Text.Json(BrokerWire.cs:1-2).Concept introduced: one definition of a contract both ends of a hop share.
[Rubric §10, Messaging & Integration Architecture]assesses whether a message survives the trip between processes unchanged. A publisher and a consumer that each build their own serializer options can drift apart one setting at a time and only disagree in production, so both ends read the one static instance here.[Rubric §13, Observability & Operability]: the broker hop is where a distributed trace most often breaks, so publish and delivery report on one named source and are parented across the broker through the W3Ctraceparentheader (BrokerWire.cs:14-19).Walkthrough:
ActivitySourceName = "MMCA.Common.Messaging"(BrokerWire.cs:19): one Producer span per publish and one Consumer span per delivery (:14-18).MessagingSystem = "mmca"(BrokerWire.cs:22): themessaging.systemtag value stamped on both spans.ActivitySource(BrokerWire.cs:25): the single shared source built from the name.JsonOptions(BrokerWire.cs:33): the very instanceOutboxMessage.SerializerOptions(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/OutboxMessage.cs:28), a plainnew(), so the System.Text.Json defaults apply and a reference cycle throws rather than being silently cut. An event that round-trips through the outbox therefore round-trips through the broker in exactly the same shape (BrokerWire.cs:27-32).
Why it's built this way: the options are a shared reference rather than a copy, so a change to one hop's options cannot leave the other behind (
BrokerWire.cs:30-31);OutboxMessagekeeps its instanceinternalprecisely so the broker wire can serialize with it (OutboxMessage.cs:25-26). The source name is a literal that MMCA.Common.Aspire subscribes by name, because that package has no reference to Infrastructure (BrokerWire.cs:16-17,MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:90).Where it's used:
BrokerMessageBusstarts the Producer span, stampsmessaging.systemand serializes the body withJsonOptions(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:70,:73,:83);BrokerReceivePipelinedeserializes with the same options and starts the Consumer span named after the host's queue (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:157,:282,:285).
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
BrokerConsumerKind
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerConsumerKind.cs:4· Level 0 · enum
- What it is: says how a host consumes one subscribed integration event:
Current = 0delivers it to the handlers of its own type,Upcasted = 1treats it as a retired contract that is upcast to its terminal successor first (BrokerConsumerKind.cs:7,10). - Depends on: nothing first-party.
- Concept: a two-value switch carried on every
BrokerSubscription; the upcasting idea itself belongs to ADR-090 and is taught atUpcastingIntegrationEventConsumer<TEvent>. - Walkthrough: explicit numeric values (
BrokerConsumerKind.cs:7,10), withCurrentas the default. - Why it's built this way: one subscription list serves both kinds, so the receive pipeline needs only this flag to pick the consumer type:
BrokerConsumerBuildermapsUpcastedtoUpcastingIntegrationEventConsumer<>and anything else toIntegrationEventConsumer<>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:40-44). - Where it's used: set by
RegisterIntegrationEventConsumer(BrokerConsumerBuilder.cs:22) andRegisterUpcastedIntegrationEventConsumer(BrokerConsumerBuilder.cs:27), and named in the duplicate-registration error (BrokerConsumerBuilder.cs:56).
BrokerDisposition
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerDisposition.cs:8· Level 0 · record (abstract)
- What it is: the closed set of outcomes the framework receive pipeline hands back to a transport for one delivered message: complete it, redeliver it later, or dead-letter it.
- Depends on:
BrokerHeaders(the redelivery-count header theRedelivercase documents,BrokerDisposition.cs:18). - Concept introduced, the disposition as a value.
[Rubric §10, Messaging & Integration]assesses whether delivery, retry and poison handling are explicit and consistent across transports; here the decision about a message is made once, in transport-neutral code, and returned as data, so every transport (RabbitMQ, PostgreSQL, Azure Service Bus, Amazon SQS) only has to apply a verdict it did not compute.[Rubric §2, Design Patterns]: an abstract record with nested sealed records is the C# shape of a discriminated union; consumersswitchon the three cases. - Walkthrough:
Complete(BrokerDisposition.cs:11) is a shared singletonCompletedinstance; the three nested cases areCompleted(:14),Redeliver(:24) andDeadLetter(:33). The doc comments define the contract each transport implements:Redeliverenqueues a delayed copy with every other header and the body unchanged, then acknowledges the original (BrokerDisposition.cs:16-21);DeadLettermoves the message to the dead-letter location with reason and detail "where the broker allows", then acknowledges it (BrokerDisposition.cs:26-30). - Why it's built this way: retry, redelivery and dead-lettering live once in the framework pipeline and
BrokerTransportPolicies, shared by every transport (MMCA.Common/AGENTS.md, Microservices Extraction Boundaries); the poison and redelivery policy is ADR-087, and the native-transport extension point is ADR-118. - Where it's used: produced by
BrokerReceivePipeline(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:98,125,191,201) and applied byRabbitMqDispositionApplier,PostgreSqlDispositionApplierand the cloud adapters' delivery handlers (MMCA.Common/Source/Hosting/MMCA.Common.Azure/Messaging/AzureServiceBusDeliveryHandler.cs,MMCA.Common/Source/Hosting/MMCA.Common.Aws/Messaging/AmazonSqsDeliveryHandler.cs, per the brief's usage sites).
BrokerHeaders
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerHeaders.cs:8· Level 0 · class (static)
- What it is: the header-name constants that make up the framework's wire contract on every broker.
- Depends on: nothing first-party.
- Concept: a shared wire vocabulary.
[Rubric §9, API & Contract Design]assesses whether a contract is explicit and stable; here the message envelope is a fixed set of named headers independent of any broker SDK, so a publisher on one transport and the receive pipeline agree on names by construction. - Walkthrough:
EventName = "mmca-event-name"(BrokerHeaders.cs:11, the receiver resolves the subscription and CLR type from it);MessageId = "mmca-message-id"(:14, the key the inbox dedupes on);RedeliveryCount = "mmca-redelivery-count"(:17, absent means none);ContentType = "content-type"(:20) withJsonContentType = "application/json"(:23, the only body type the framework writes);TraceParent = "traceparent"(:26) andTraceState = "tracestate"(:29) for W3C trace context. - Why it's built this way: the inbox key and the redelivery counter must survive any broker, so they travel as plain string headers rather than broker-native properties; inbox dedupe is ADR-021.
- Where it's used:
BrokerMessageBuswritesEventName,MessageId,ContentTypeand the trace headers (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:66-68,113,116);IncomingBrokerMessagereadsEventNameandRedeliveryCount(IncomingBrokerMessage.cs:17,24);BrokerReceivePipelinenames the header in its unknown-event detail (BrokerReceivePipeline.cs:151). - Caveats / not-in-source: the
MMCA-*ambient-origin headers restored by the consumer are not declared here; they belong toAmbientOrigin.
Completed
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerDisposition.cs:14· Level 0 · record (sealed, nested inBrokerDisposition)
- What it is: the
BrokerDispositioncase meaning "handled, or deliberately skipped as a duplicate: acknowledge and remove it" (BrokerDisposition.cs:13). - Depends on:
BrokerDisposition. - Concept: see
BrokerDisposition. - Walkthrough: no members; callers use the shared
BrokerDisposition.Completeinstance (BrokerDisposition.cs:11) rather than allocating one. - Where it's used: returned when the consumer succeeds (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:125), then matched by each transport's disposition applier. - Caveats / not-in-source: several usage sites the inventory lists for the name
Completed(for exampleUsersAdminControllerBase.cs,OfflineWriteQueueTests.cs) are unrelated identifiers that share the name, not this record.
OutgoingBrokerMessage
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/OutgoingBrokerMessage.cs:13· Level 0 · record (sealed)
- What it is: a serialized integration event ready to publish:
Topic,EventName,MessageId,BodyandHeaders(OutgoingBrokerMessage.cs:13-18). - Depends on: BCL only (
ReadOnlyMemory<byte>,IReadOnlyDictionary<string, string>). - Concept: the transport-neutral publish envelope; its receive-side twin is
IncomingBrokerMessage. - Walkthrough: a positional record;
Bodyis already-serialized bytes andHeaderscarries theBrokerHeadersentries.EventNameandMessageIdduplicate header values as typed fields so a transport need not parse them back. - Why it's built this way: the serializer and header stamping run once in
BrokerMessageBus(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs:86), so each publisher only maps an envelope onto its SDK. - Where it's used: the only argument of
IBrokerPublisher.PublishAsync(IBrokerPublisher.cs:18), and of the PostgreSQL message store (IPostgreSqlMessageStore).
BrokerSubscription
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerSubscription.cs:11· Level 1 · record (sealed)
- What it is: one integration event a host consumes: its wire
EventName, CLREventType, theTopicit is published on, and itsBrokerConsumerKind(BrokerSubscription.cs:11). - Depends on:
BrokerConsumerKind. - Concept: the unit of
BrokerTopology; a transport binds one topic per subscription to the host's queue. - Walkthrough: a one-line positional record.
- Why it's built this way: name and topic are computed once at registration with
BrokerNaming(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:49,60), so the receiver never recomputes them per message. - Where it's used: built by
BrokerConsumerBuilder(BrokerConsumerBuilder.cs:60), held byBrokerTopology, and looked up byBrokerReceivePipeline(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:145).
DeadLetter
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerDisposition.cs:33· Level 1 · record (sealed, nested inBrokerDisposition)
- What it is: the
BrokerDispositioncase for a message that cannot be handled: move it to the dead-letter location withReasonandDetail, then acknowledge it (BrokerDisposition.cs:26-33). - Depends on:
BrokerDisposition. - Concept: see
BrokerDisposition; poison handling is ADR-087. - Walkthrough:
Reasonis a short machine-friendly string andDetaila nullable human-readable description (BrokerDisposition.cs:31-32). The pipeline uses three reasons:unknown-event,poisonandhandler-failed(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:30,33,36). An unknown event or an undeserializable body is dead-lettered immediately, since no retry can fix it (BrokerReceivePipeline.cs:149,162,169); a handler failure is dead-lettered only after every redelivery is spent (BrokerReceivePipeline.cs:187-201). - Where it's used: produced by
BrokerReceivePipeline; applied by each transport's disposition applier or delivery handler.
IBrokerPublisher
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerPublisher.cs:9· Level 1 · interface
- What it is: the publish half of a broker transport: one method,
PublishAsync(OutgoingBrokerMessage, CancellationToken)(IBrokerPublisher.cs:18). - Depends on:
OutgoingBrokerMessage. - Concept: a narrow port per transport.
[Rubric §1, SOLID](interface segregation, dependency inversion): the framework's bus depends on this one-method abstraction, and each transport supplies only an implementation, so adding a broker never touches the publish path. - Walkthrough: the contract carries the body and every header unchanged, and when
MessageBus:ProvisionTopologyis set a missing topic is created first (IBrokerPublisher.cs:12-13). The returned task completes when the broker has accepted the message (IBrokerPublisher.cs:17). - Why it's built this way: a transport registers "only its
IBrokerPublisherand its hosted receiver"; everything else is shared framework code (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:44-46;MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/IBrokerTransport.cs:38). See ADR-118 and ADR-134. - Where it's used: consumed by
BrokerMessageBus(BrokerMessageBus.cs:47); implemented byRabbitMqPublisher,PostgreSqlPublisher, and the Azure Service Bus and Amazon SQS publishers in the vendor adapters.
IncomingBrokerMessage
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IncomingBrokerMessage.cs:11· Level 1 · record (sealed)
- What it is: a delivered message as the receive pipeline sees it:
Body,Headers, and the broker's ownBrokerMessageId(IncomingBrokerMessage.cs:11-14). - Depends on:
BrokerHeaders. - Concept: the receive-side envelope, the twin of
OutgoingBrokerMessage. - Walkthrough:
EventName(IncomingBrokerMessage.cs:17) reads themmca-event-nameheader or returnsnull.RedeliveryCount(IncomingBrokerMessage.cs:23-27) parses themmca-redelivery-countheader withNumberStyles.Noneand the invariant culture, so an absent or malformed value (including a sign) reads as zero. - Why it's built this way: tolerant parsing means a tampered or foreign header degrades to "first attempt" rather than throwing inside the receive loop.
BrokerMessageIdis kept separate from the event's ownMessageIdheader because it is only used for logging the broker-side delivery (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:148,161). - Where it's used: built by each transport receiver (for example
RabbitMqReceiver,PostgreSqlReceiver) and the vendor message mappings, then passed toIBrokerReceivePipeline.
Redeliver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerDisposition.cs:24· Level 1 · record (sealed, nested inBrokerDisposition)
- What it is: the
BrokerDispositioncase for a second-level redelivery: enqueue a copy visible afterDelaywith the redelivery-count header set toRedeliveryCount, then acknowledge the original (BrokerDisposition.cs:16-24). - Depends on:
BrokerDisposition,BrokerHeaders. - Concept: second-level redelivery per ADR-087: after in-process retries fail, the message leaves the consumer and comes back later, instead of holding the delivery.
- Walkthrough:
BrokerReceivePipelinereturns it whileredeliveryCount < _redeliveryIntervals.Length, taking the delay from the interval at the current count and incrementing the count (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:187-191); the count read comes fromIncomingBrokerMessage.RedeliveryCount(BrokerReceivePipeline.cs:129). - Where it's used: applied by the transport appliers and vendor delivery handlers, each with its own delay mechanism.
- Caveats / not-in-source: the redelivery interval values come from settings and the transport's
MaxRedeliveryDelay(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:108-121); the defaults are not shown in these files.
BrokerNaming
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerNaming.cs:13· Level 2 · class (static)
- What it is: the deterministic naming rules for broker entities: event wire names, topics, the host queue name, length fitting, and kebab casing.
- Depends on:
EventNameResolver(BrokerNaming.cs:29, for anEventNameAttributedeclared name); BCLSHA256,StringBuilder. - Concept: naming as a pure function.
[Rubric §7, Microservices Readiness]assesses whether services can be split and redeployed independently; because every host derives the same names from the same inputs, a publisher and a separately deployed consumer agree on topics without shared configuration. - Walkthrough:
EventName(Type)(BrokerNaming.cs:25-30): kebab-case of the declared[EventName]when present, otherwise the CLR full name, so equal short names in different modules never share a topic.Topic(applicationNamespace, eventName)(BrokerNaming.cs:36-42):{kebab(namespace)}-{eventName}.Queue(configured, applicationName)(BrokerNaming.cs:53-69): the configuredMessageBus:QueueNamewhen set, else the kebab application name with a trailing-servicetrimmed (only when derived, and only if something remains); throwsInvalidOperationExceptionwhen neither yields a name.Fit(name, maxLength)(BrokerNaming.cs:80-92): returns a name within the limit unchanged; otherwise keeps the prefix and appends-plus the first 8 lowercase hex digits of its SHA-256.maxLengthmust be at least 16 (:83).Kebab(value)(BrokerNaming.cs:97-130): lowercases ASCII letters and digits, collapses every other run to one-, and also breaks at a lower-to-upper boundary (UserRegisteredbecomesuser-registered,:110-113).
- Why it's built this way: topics are prefixed with the application namespace so two applications sharing a broker never publish onto each other's topics (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:86-89). The hash suffix inFitkeeps two long names distinct and identical on every host (BrokerNaming.cs:71-75). - Where it's used:
BrokerConsumerBuilder(BrokerConsumerBuilder.cs:49,60),BrokerTopology.TopicFor(BrokerTopology.cs:55),AddBrokerMessagingfor the queue (DependencyInjection.Messaging.cs:96),RabbitMqNames, and the Azure and AWS entity-name helpers; ADC'sBrokerTopologyBicepTestschecks infrastructure names against it.
IBrokerConsumerBuilder
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerConsumerBuilder.cs:16· Level 2 · interface
- What it is: the fluent registration surface a host uses to declare which integration events it consumes from the broker.
- Depends on:
IIntegrationEvent(the generic constraint). - Concept: declarative subscription.
[Rubric §10, Messaging & Integration]: a host lists its consumed events once, and the topology, the per-subscription consumer registration and the broker bindings are all derived from that list. - Walkthrough:
RegisterIntegrationEventConsumer<TEvent>()(IBrokerConsumerBuilder.cs:26-27) delivers each message to everyIIntegrationEventHandler<TEvent>in the host through the inbox.RegisterUpcastedIntegrationEventConsumer<TEvent>()(IBrokerConsumerBuilder.cs:40-41) drains a retired contract, upcasting it to its terminal successor and delivering to that contract's handlers; pair it withAddEventUpcaster<TEvent, TNew, TUpcaster>()and a plain registration for the current contract, never register both kinds for the same type, and with no upcaster registered it degrades to ordinary dispatch (IBrokerConsumerBuilder.cs:30-35). Both throwInvalidOperationExceptionwhen the type is already registered (:25,39). - Why it's built this way: registering the same event both ways would bind two consumers to one wire name; the builder rejects it by type or by wire name (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:51-58). Upcasting is ADR-090. - Where it's used: implemented by
BrokerConsumerBuilder, passed to theconfigureConsumerscallback ofAddBrokerMessaging(DependencyInjection.Messaging.cs:91-92); ADC's per-service registrations (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/ConferenceBrokerConsumers.cs,EngagementBrokerConsumers.cs,IdentityBrokerConsumers.cs) call it.
IBrokerReceivePipeline
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/IBrokerReceivePipeline.cs:16· Level 2 · interface
- What it is: the transport-neutral handling of one delivered message:
ProcessAsync(IncomingBrokerMessage, CancellationToken)returning aBrokerDisposition(IBrokerReceivePipeline.cs:22). - Depends on:
IncomingBrokerMessage,BrokerDisposition. - Concept: the split between "decide" and "apply".
[Rubric §14, Testability]assesses whether behavior can be verified without infrastructure; because the decision is a pure function of message and handler outcome returning a value, the pipeline is unit-tested without a broker and each transport is tested only on how it applies the three dispositions. - Walkthrough: one method; the cancellation token fires when the host is stopping (
IBrokerReceivePipeline.cs:20). - Why it's built this way: the framework pipeline owns trace context, origin restore, inbox, retry and dead-lettering, and a transport only receives and applies (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:44-46;MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/IBrokerTransport.cs:13,38-40). - Where it's used: registered as a singleton
BrokerReceivePipeline(DependencyInjection.Messaging.cs:117); called byRabbitMqReceiver,PostgreSqlReceiver, and the Azure and AWS delivery handlers.
BrokerTopology
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Broker·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Broker/BrokerTopology.cs:10· Level 3 · class (sealed)
- What it is: a host's complete broker shape: the application namespace topics are prefixed with, the host's queue name, and the subscriptions bound to that queue, with lookup by wire name.
- Depends on:
BrokerSubscription,BrokerNaming,BrokerHeaders(doc reference). - Concept: one immutable description that every transport provisions from and the receive pipeline routes by.
[Rubric §13, Observability & Operability](as configuration safety): a duplicate subscription fails at startup, not as a silently misrouted message. - Walkthrough: the constructor (
BrokerTopology.cs:19-41) guards its arguments, rejects two subscriptions with the same event name with anInvalidOperationExceptionnaming both registration methods (:25-34), and indexes the rest in an ordinal dictionary (:36).ApplicationNamespace,QueueNameandSubscriptions(registration order) are read-only properties (:44,47,50).TopicFor(Type)composesBrokerNaming.Topicand.EventName(:55).TryGetSubscription(eventName, out subscription)is the per-message lookup (:61-62). - Why it's built this way:
BrokerConsumerBuilderalready rejects duplicates (BrokerConsumerBuilder.cs:51-58); the constructor repeats the check because the topology is public and can be built directly (as tests do). - Where it's used: built once and registered as a singleton by
AddBrokerMessaging(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:94-99), which also registers one scoped consumer per subscription (:103-106). Read byBrokerReceivePipeline(BrokerReceivePipeline.cs:145),BrokerMessageBus,BrokerTransportContext, and every receiver and provisioner.
MessageBusProviders
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/MessageBusProviders.cs:10· Level 0 · class (public static)
What it is: the vocabulary of
MessageBus:Provider. Three public string constants name the transports the core package ships (InProcess,RabbitMq,PostgreSql), three internal predicates compare a configured value against them case-insensitively, and an internal lookup table names the adapter package and registration call for the two cloud transports the framework knows about (MessageBusProviders.cs:10-58).Depends on: nothing first-party. BCL only (
StringComparer.OrdinalIgnoreCase,string.Equals).Concept introduced, transport selection as a configuration string.
[Rubric §7, Microservices Readiness]assesses whether the move from one process to many is a deployment change rather than a code change, and this class is where that move is spelled. The same host binary runs as a modular monolith withInProcess(the default when the setting is blank,:12-16), as a development microservice deployment onRabbitMq(:18-19), or on the built-in PostgreSQL transport against any PostgreSQL database withPostgreSql(:21-27).[Rubric §33, Developer Experience]assesses whether a misconfiguration tells the developer how to fix it:KnownAdapterTransportsexists only to make the "unknown provider" error actionable, and its doc says it registers nothing (:29-33). The provider switch itself is ADR-066; the cloud-neutral split behind the adapter table is ADR-134.Walkthrough
InProcess = "InProcess"(MessageBusProviders.cs:16),RabbitMq = "RabbitMq"(:19),PostgreSql = "PostgreSql"(:27). ThePostgreSqldoc stresses that the broker is a database, not a cloud service, so any managed or self-hosted PostgreSQL serves (:21-26).KnownAdapterTransports(:34-39) is anOrdinalIgnoreCasedictionary of(Package, Registration)pairs:AzureServiceBusmaps toMMCA.Common.Azureandservices.AddAzureServiceBusTransport()(:37),AmazonSqstoMMCA.Common.Awsandservices.AddAmazonSqsTransport()(:38).IsInProcess(provider)(:44-45) is true for a null, empty or whitespace value as well as forInProcess, which is what makes in-process dispatch the zero-configuration default.IsRabbitMq(:50-51) andIsPostgreSql(:56-57) are plain case-insensitive equality checks.
Why it's built this way: keeping the names as constants in one place means the selection logic, the outbox default and the startup summary compare against the same strings. Keeping the adapter table internal and descriptive (a package name plus a call, never a type reference) is what lets the core package name a cloud transport in an error message without referencing its SDK, which ADR-134 forbids.
Where it's used:
AddBrokerMessagingreturns before registering any broker service whenIsInProcessholds (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:72).ResolveBrokerTransport(DependencyInjection.Messaging.cs:214) returns RabbitMqBrokerTransport or PostgreSqlBrokerTransport for the built-in names (:201-208), and otherwise builds its failure from these members: the available list starts with the three constants (:225) and the remedy quotes theKnownAdapterTransportsentry when one matches (:226). MessageBusSettings resolves the inbox and outbox defaults fromIsInProcess(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:142,:180), and each built-in transport returns its constant as itsName. StartupConfigurationSummaryService also references the type.Caveats / not-in-source:
KnownAdapterTransportscarries only the Azure and AWS entries; a provider name for any other adapter falls through to the generic "register anIBrokerTransportnamed ..." remedy (DependencyInjection.Messaging.cs:243).
PostgreSqlClaimedMessage
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlClaimedMessage.cs:14· Level 0 · record (internal sealed)
What it is: one row of the PostgreSQL transport's
messagestable as a receiver holds it after a claim: the rowId, theLockTokenthat proves the claim, the applicationMessageId, the headers, the body bytes and theDeliveryCount(PostgreSqlClaimedMessage.cs:14-20).Depends on: nothing first-party. BCL types only.
Concept: the claim-under-a-lease model is taught at IPostgreSqlMessageStore. What matters about this record is that
IdandLockTokentravel together: every settle statement matches on both, so a receiver whose lease passed to another claim changes nothing.Walkthrough
- Six positional members (
PostgreSqlClaimedMessage.cs:15-20).Headersis anIReadOnlyDictionary<string, string>(:18) andBodyabyte[](:19). - PostgreSqlMessageStore builds one per row the claim statement returns, stamping the one lock token it generated for the whole batch (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlMessageStore.cs:103,:119-125).
- Six positional members (
Why it's built this way: a positional record keeps the claim result immutable, so the receiver can hand the same instance to the pipeline, the lease renewer and the settle call without one of them changing what the others see.
Where it's used: returned by
IPostgreSqlMessageStore.ClaimAsyncand passed back to every settle and renew method (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/IPostgreSqlMessageStore.cs:36-71). PostgreSqlReceiver tracks the in-flight ones byId(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiver.cs:53), and PostgreSqlDispositionApplier settles them. The test doubleMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/FakePostgreSqlMessageStore.csbuilds them directly.
PostgreSqlTransportSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlTransportSettings.cs:8· Level 0 · class (internal sealed)
What it is: the
MessageBus:PostgreSqlsub-section that tunes the built-in PostgreSQL transport: the schema the broker's tables live in, the role the migration creates and makes their owner, whether this host runs that migration at startup, and how long dead letters are kept (PostgreSqlTransportSettings.cs:8-54). Everything else (connection string, retry, redelivery, backpressure, topology provisioning) comes from the sharedMessageBussection.Depends on: nothing first-party. Plain
initproperties read throughIConfiguration'sGet<T>().Concept: the parent section and its options shape are taught at MessageBusSettings.
[Rubric §8, Data Architecture]applies to the default schema: the broker can share a database with the application's own tables because its tables sit in their owntransportschema (:16-20).[Rubric §17, DevOps]applies toMigrateOnStartup: the migration needs rights to create a role and a schema, so a host whose database user has neither turns the switch off and creates the schema out of band, which is safe because the DDL is idempotent (:30-35).Walkthrough
SectionPath = "MessageBus:PostgreSql"(PostgreSqlTransportSettings.cs:11) andDefaultName = "transport"(:14), the default for both the schema and the role.Schema(:21) andRole(:28) are nullable; their docs state the identifier rule (a letter or underscore, then letters, digits or underscores, at most 63 characters,:18-19,:27).EffectiveSchema(:50) andEffectiveRole(:53) fall back toDefaultNamewhen the configured value is null or whitespace.Roleis the role the migration creates when missing, grants to the connecting user, and makes the owner of the schema and its tables, so every service that connects as a member of it can use the transport (:23-27).MigrateOnStartup(:36) defaults totrue.DeadLetterRetentionDays(:44) defaults toDefaultDeadLetterRetentionDays, 30 (:47): how many days a dead letter stays indead_letters, counted from when it was dead-lettered, before the hourly sweep deletes it. Zero or less keeps dead letters forever, and the sweep still records the depth gauge; the sweep runs on the consuming hosts, over each host's own queue, on one replica per hour (:38-43).
Why it's built this way: the doc on
MigrateOnStartupnames the constraint directly (PostgreSqlTransportSettings.cs:30-35): creating a role and a schema is a privilege an application user often lacks, so a deployment needs a way to run the migration once from a host that has it. The type isinternalbecause only the transport reads it.Where it's used: PostgreSqlBrokerTransport reads it through
ReadSettings, which falls back to a default instance when the section is absent (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:113-115).RegisterfeedsEffectiveSchemaandEffectiveRoleinto PostgreSqlTransportSql (:71), usesMigrateOnStartupto decide whether to register PostgreSqlSchemaMigrator and whether the publisher and receiver ensure the schema first (:72,:76,:79-82,:89), and passesDeadLetterRetentionDaysto PostgreSqlDeadLetterCleanupService (:104). Also read byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.PostgreSQL.Tests/PostgreSqlBrokerTransportTests.cs.Caveats / not-in-source: the section carries no validation attributes and is read with
Get<T>(); the identifier rule is enforced later, when PostgreSqlTransportSql is constructed duringRegister(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlTransportSql.cs:35-36), so a bad name fails at startup rather than at bind time.
IPostgreSqlMessageStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/IPostgreSqlMessageStore.cs:10· Level 1 · interface (internal)
What it is: every database operation the PostgreSQL transport performs, as thirteen async methods: create the schema, bind topics to a queue, publish, claim, the four settle outcomes (complete, redeliver, dead-letter, release), renew leases, ask when the next row is due, purge and count dead letters, and listen for publish notifications (
IPostgreSqlMessageStore.cs:10-102).Depends on: OutgoingBrokerMessage and PostgreSqlClaimedMessage.
Concept introduced, a database table as a queue under leased claims.
[Rubric §10, Messaging and Integration]assesses whether delivery semantics are explicit rather than inherited from a vendor. Here they are spelled out in the method contracts: a claim takes up tolimitdue rows "under a lease" (:30-36), and every settle method returnsfalse"when the lease was lost (another claim holds the row)" (:41,:49,:57,:63). A crashed receiver therefore loses nothing: its lease expires and the row becomes claimable again, which is at-least-once delivery that the inbox then dedupes (ADR-021).[Rubric §29, Resilience and Business Continuity]applies toListenAsync: it throws when the connection fails (:93-96), and the receiver falls back to polling rather than stalling.Walkthrough
EnsureSchemaAsync(IPostgreSqlMessageStore.cs:15) runs the migration once per process; a failed attempt is retried on the next call (:12).SubscribeAsync(queue, topics)(:22) andPublishAsync(message)(:28): publish inserts one row per queue subscribed to the message's topic and signals those queues (:24).ClaimAsync(queue, limit, lease)(:36) returns the claimed rows, possibly none.CompleteAsyncdeletes a handled row (:42);RedeliverAsync(message, delay, headers)hides it fordelaywith new headers and releases the claim (:50);DeadLetterAsync(message, reason, detail)moves it todead_letters(:58);ReleaseAsyncfrees the claim without settling, so the row is claimable at once (:64).RenewAsync(messages, lease)(:71) extends the lease of every row still held;NextDueAsync(queue)(:77) returns the wait until the next claimable row, or null for an empty queue.PurgeDeadLettersAsync(queue, retention, limit)(:85) deletes up tolimitof the queue's dead letters older thanretention, oldest first, and returns how many it deleted (:79,:84);CountDeadLettersAsync(queue)(:91) returns the queue's dead-letter count.ListenAsync(queue, notified)(:101) callsnotifiedper notification and once when listening starts (:98).
Why it's built this way: putting the SQL behind an interface separates the receiver's concurrency logic from the database, so PostgreSqlReceiver and PostgreSqlDispositionApplier are unit-tested against
MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/FakePostgreSqlMessageStore.cswithout a server.Where it's used: implemented by PostgreSqlMessageStore. Consumed by PostgreSqlReceiver, PostgreSqlPublisher, PostgreSqlSchemaMigrator, PostgreSqlDispositionApplier and PostgreSqlDeadLetterCleanupService.
BrokerTransportPolicies
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/BrokerTransportPolicies.cs:18· Level 2 · class (public static)
What it is: the receive-side policies every broker transport shares, as pure functions of MessageBusSettings: the exponential in-process retry delay, the second-level redelivery intervals (clamped to a transport's delay cap), and the back-off before a message whose settle failed is offered again (
BrokerTransportPolicies.cs:18-87). The two backpressure knobs are deliberately not here: each transport readsPrefetchCountandConcurrentMessageLimitdirectly, and a value below 1 has already failed the host at start (:7-9).Depends on: MessageBusSettings only. No transport library.
Concept introduced, one failure policy across interchangeable transports.
[Rubric §10, Messaging and Integration]assesses whether poison and transient failures are handled deliberately rather than by each transport's defaults, and[Rubric §29, Resilience and Business Continuity]assesses whether a transient fault is absorbed before it becomes a dead letter. Because IBrokerTransport lets an adapter package supply the transport, the retry and redelivery numbers would otherwise be re-derived (and drift) per broker. This class is the single definition: the framework receive pipeline reads the retry delay and redelivery intervals from it. In-process retry absorbs a blip measured in seconds; second-level redelivery re-enqueues the message over one minute, ten minutes and one hour by default (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:196), so an outage measured in minutes or hours does not dead-letter the event, and every in-process retry is exhausted before a redelivery is asked for (:11-17). Poison-message handling is ADR-087; the library policy that keeps the transports as framework code is ADR-118.Walkthrough
SettleFailureBackoff(BrokerTransportPolicies.cs:27) is an internal 30-second wait before a message whose settle failed (the pipeline decided, but the ack, delete, redelivery or dead-letter write did not go through) is offered again. Without it a settle that fails every time (a missing permission, a broken dead-letter location) would re-deliver the message at once in a hot loop (:20-26).RetryDelay(settings, retryNumber)(:38-51) rejects a retry number below 1 (:41), doublesRetryMinIntervalSecondsper retry and caps the result atRetryMaxIntervalSeconds(:43-48), with the exponent capped at 30 (:47). With the defaults (1 and 30 seconds) the five retries wait 1, 2, 4, 8 and 16 seconds (:32-33);RetryLimitdefaults to5(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:94).BuildRedeliveryIntervals(settings)(:63-64) delegates to the two-argument overload with no cap.BuildRedeliveryIntervals(settings, maxRedeliveryDelay)(:76-86) falls back toMessageBusSettings.DefaultRedeliveryIntervalsSecondswhen nothing is configured (:82), drops non-positive entries (:83), and shortens every interval longer than the cap to the cap (:85). A null or non-positive cap means no cap (:80). A zero interval is dropped because it would redeliver immediately, which is what the in-process retry already does, and an empty result turns second-level redelivery off (:56-59).- The backpressure knobs have no function here.
PrefetchCountandConcurrentMessageLimitcarry[Range(1, int.MaxValue)]and are validated when the host starts, so a value below 1 never reaches a transport (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:225-229,:230-233); each transport applies its own default to a null value.
Why it's built this way: as pure functions with no transport type in their signatures, the policies can be shared by transports that have nothing else in common (an AMQP channel, a PostgreSQL table, a cloud SDK receiver), and they are trivially unit-tested. Backpressure needs no shared policy once startup validation rejects a non-positive value: what is left is each broker's own default for an unset knob, which differs per transport and so belongs to the transport.
Where it's used: BrokerReceivePipeline builds its intervals with the transport's
MaxRedeliveryDelay(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:87) and waitsRetryDelaybetween attempts (:197). PostgreSqlReceiver hides a row whose settle failed forSettleFailureBackoff(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiver.cs:306) and RabbitMqReceiver waits it out before the message is offered again (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqReceiver.cs:251); both count the failure on BrokerMetrics'SettleFailureCounter(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMetrics.cs:42). No transport calls it for backpressure: PostgreSqlReceiverOptions (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiverOptions.cs:52-53), RabbitMqBrokerTransport (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqBrokerTransport.cs:108,:105),AmazonSqsReceiver(MMCA.Common/Source/Hosting/MMCA.Common.Aws/Messaging/AmazonSqsReceiver.cs:74,:80) andAzureServiceBusReceiver(MMCA.Common/Source/Hosting/MMCA.Common.Azure/Messaging/AzureServiceBusReceiver.cs:87-88) each read the two settings directly. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/BrokerTransportPoliciesTests.cs.Caveats / not-in-source: the cap clamps rather than rejects, so a configured interval longer than a broker allows (Amazon SQS caps a delay at 15 minutes,
:70-71) runs at the cap without an error.SettleFailureBackoffis a fixed constant, not a configuration key.
PostgreSqlDeadLetterCleanupService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlDeadLetterCleanupService.cs:20· Level 2 · class (internal sealed partial)
What it is: the PostgreSQL transport's dead-letter retention sweep: every hour, on one replica of the host, it deletes the host queue's
dead_lettersrows older than the configured retention in batches, oldest first, and records the queue's remaining dead-letter depth on a gauge (PostgreSqlDeadLetterCleanupService.cs:7-20). Without it the table only grows, and nothing reports how many events are waiting for triage (:12).Depends on: PeriodicBackgroundService (its base), IPostgreSqlMessageStore, IDistributedLock (optional), BrokerMetrics, PostgreSqlTransportSettings (the source of the retention); BCL
TimeProvider.Concept: the receive-side failure policy that produces dead letters is taught at BrokerTransportPolicies, and the leased-claim store at IPostgreSqlMessageStore.
[Rubric §8, Data Architecture]applies to retention: the sweep runs against the broker database over the host's own queue only, so each consuming service owns its dead letters (:14-15).[Rubric §10, Messaging and Integration]applies to the depth gauge: it is recorded even when retention is off, so a growing backlog of failed events stays visible (:15-16).Walkthrough
BatchSizeis 1000, the most rows one delete statement removes (PostgreSqlDeadLetterCleanupService.cs:23).- The constructor (
:40-57) takes the store, the queue (null or whitespace throws,:50), the retention in days, an optional cycle lock, aTimeProviderand a logger, and hands the clock and logger to the base (:47). Intervalis one hour (:60);CycleLockreturns the injected lock (:63), which is what runs the cycle on one replica per interval.ExecuteCycleAsync(:66-82) purges only when the retention is positive (:68-70), logs a Warning with the count when it deleted anything (:73), then counts the queue's dead letters (:77) and records the count onBrokerMetrics.DeadLetterDepthGaugetaggedtransport=postgresqland the queue name (:78-81,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMetrics.cs:52).PurgeAsync(:84-96) callsPurgeDeadLettersAsyncinBatchSizebatches until a batch comes back short or the host stops (:93).LogPurged(:98-99) is a Warning, because the deletion destroys the only record that those events failed (:16-17).
Why it's built this way: batching keeps each delete statement bounded (the purge statement walks the
(queue, dead_lettered_at)index,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlTransportSql.cs:150-154), so a first sweep over a large backlog does not hold one long transaction. Scoping each sweep to the host's own queue keeps one service's retention from deleting another service's evidence.Where it's used: registered as a hosted service by PostgreSqlBrokerTransport on every consuming host, after the receiver, with
DeadLetterRetentionDays, a resolved (not required)IDistributedLockandTimeProvider.Systemas the fallback clock (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:98-107). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlDeadLetterCleanupServiceTests.cs.Caveats / not-in-source: because the lock is resolved rather than required, a broker host that skipped
AddInfrastructurestill sweeps, but on every replica (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:98-100). A publish-only host registers no sweep, so dead letters of a queue no host consumes are never purged.
PostgreSqlDispositionApplier
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlDispositionApplier.cs:17· Level 2 · class (internal static)
What it is: the one function that turns a BrokerDisposition returned by the receive pipeline into the matching IPostgreSqlMessageStore settle call (
PostgreSqlDispositionApplier.cs:17-49).Depends on: IPostgreSqlMessageStore, PostgreSqlClaimedMessage, BrokerDisposition and its Redeliver and DeadLetter cases, BrokerHeaders.
Concept: the pipeline-decides, transport-acts split is taught at IBrokerTransport; this is the PostgreSQL transport's half of it.
Walkthrough
ApplyAsync(store, message, disposition, cancellationToken)(PostgreSqlDispositionApplier.cs:25-48) null-guards its three references (:31-33) and switches on the disposition (:35).RedelivercallsRedeliverAsyncwith the redelivery delay and a copy of the row's headers in whichBrokerHeaders.RedeliveryCountis set to the new count (:37-44).DeadLettercallsDeadLetterAsyncwith the reason and detail (:45); anything else completes the row (:46).- The result is the store's:
falsemeans the lease had already been lost and another claim owns the row (:22).
Why it's built this way: carrying the redelivery count in the row's headers is what lets the next delivery's pipeline know which redelivery interval comes next, since the row itself is re-used rather than re-published. Keeping the mapping in a static function makes every branch testable without a receiver.
Where it's used: PostgreSqlReceiver calls it after each pipeline run (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiver.cs:259). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlDispositionApplierTests.cs.
PostgreSqlPublisher
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlPublisher.cs:13· Level 2 · class (internal sealed)
What it is: the PostgreSQL transport's IBrokerPublisher: it ensures the schema exists when this host migrates at startup, then hands the message to the store's fan-out insert (
PostgreSqlPublisher.cs:13-27).Depends on: IPostgreSqlMessageStore, IBrokerPublisher, OutgoingBrokerMessage.
Concept: the publisher contract is taught at IBrokerPublisher.
Walkthrough
- Primary constructor over the store and a
migrateOnStartupflag (PostgreSqlPublisher.cs:13). PublishAsync(:16-26) null-guards the message, awaitsEnsureSchemaAsyncwhenmigrateOnStartupis set (:20-23), thenstore.PublishAsync(:25).
- Primary constructor over the store and a
Why it's built this way: the outbox processor can publish before the hosted PostgreSqlSchemaMigrator has finished, and the store's
EnsureSchemaAsyncruns the migration only once per process (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlMessageStore.cs:54-67), so awaiting it here costs nothing after the first call and closes that startup race.Where it's used: registered as the singleton
IBrokerPublisherby PostgreSqlBrokerTransport (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:76). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransportTests.csandBrokerTransportRegistrationTests.csin the same test project.
PostgreSqlSchemaMigrator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlSchemaMigrator.cs:12· Level 2 · class (internal sealed)
What it is: an
IHostedServicewhoseStartAsyncis the store'sEnsureSchemaAsyncand whoseStopAsyncdoes nothing (PostgreSqlSchemaMigrator.cs:12-19).Depends on: IPostgreSqlMessageStore;
Microsoft.Extensions.Hosting.IHostedService.Concept:
[Rubric §17, DevOps]: the schema is created by the application at startup, with an opt-out at PostgreSqlTransportSettings for a host without the rights.Walkthrough
StartAsync(PostgreSqlSchemaMigrator.cs:15) returnsstore.EnsureSchemaAsync(cancellationToken);StopAsync(:18) returns a completed task.
Why it's built this way: hosted services start in registration order, and PostgreSqlBrokerTransport registers this one before the receiver, so the migration finishes before the receiver starts claiming (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:78-82).Where it's used: registered only when
MigrateOnStartupis true (PostgreSqlBrokerTransport.cs:79-82). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransportTests.cs.
PostgreSqlReceiverOptions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiverOptions.cs:11· Level 2 · record (internal sealed)
What it is: the seven values PostgreSqlReceiver runs with: concurrency, claim batch size, whether to migrate and whether to provision topology first, and the lease, renewal and poll intervals (
PostgreSqlReceiverOptions.cs:11-64).Depends on: MessageBusSettings only.
Concept: the shared receive-side policies (and why backpressure is not among them) are taught at BrokerTransportPolicies; the lease model at IPostgreSqlMessageStore.
Walkthrough
- Positional members (
PostgreSqlReceiverOptions.cs:12-18). MaxUnexplainedClaimsis 10 (:29): the most claims of one row that no redelivery explains before the receiver dead-letters it withPostgreSqlReceiver.DeliveryLimitReason. A claim is explained when the pipeline asked for a second-level redelivery (counted inmmca-redelivery-count); any other re-claim means the previous claim ended without a decision (the process died or hung on the message, the host stopped mid-message, or a settle failed), and ten leaves room for a run of deploys and settle blips a healthy message also sees (:20-28).DefaultLeaseis 60 seconds, "long enough to ride out a renewal missed to a database blip" (:31-32);DefaultRenewIntervalis 20 seconds, a third of the lease, so one missed renewal does not lose the claim (:34-35);DefaultPollIntervalis 5 seconds, the fallback when no notification arrives (:37-38).From(settings, migrateOnStartup)(:48-63): concurrency isMessageBus:ConcurrentMessageLimitread directly from the settings, elseEnvironment.ProcessorCount, at least 1 (:52); the claim batch isMessageBus:PrefetchCount, else the concurrency, clamped to[1, concurrency](:53). Neither value can arrive below 1, because the settings fail the host at start on one (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:228,:232);ProvisionTopologycomes from the shared settings (:59), which default it totrue(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:84).
- Positional members (
Why it's built this way: a batch larger than the concurrency would claim rows no worker can start, and their leases would tick while they wait, so the clamp keeps every claimed row immediately runnable. The three timings are not configuration keys; only a test adjusts them, through the internal constructor of PostgreSqlBrokerTransport.
Where it's used: built in
PostgreSqlBrokerTransport.Register(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:89-90) and passed to PostgreSqlReceiver. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlReceiverTests.cs.
PostgreSqlTransportSql
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlTransportSql.cs:24· Level 3 · class (internal sealed partial)
What it is: every SQL statement the PostgreSQL transport runs, built once per schema and role: the idempotent migration, subscribe, the fan-out publish, claim, the four settle statements, renew, next-due, the dead-letter purge and count, and
LISTEN, plus the identifier validation that makes writing the schema and role names into SQL safe (PostgreSqlTransportSql.cs:24-255).Depends on: BrokerNaming (to fit the notification channel name). BCL
GeneratedRegex,SHA256,BinaryPrimitives.Concept:
[Rubric §8, Data Architecture]applies to the three-table design:subscriptionsbinds topics to queues,messagesholds one row per queue per publish withvisible_afterand the lease columns, anddead_letterskeeps settled failures with a reason and adead_lettered_attimestamp indexed with the queue (:224-252). The claim usesFOR UPDATE SKIP LOCKED(:67), so competing receivers on several replicas take disjoint rows without blocking each other.Walkthrough
- The constructor (
PostgreSqlTransportSql.cs:33-109) validates the schema and role againstMessageBus:PostgreSql:Schemaand:Role(:35-36), derivesNotifyChannelas{schema}_messagesfitted toMaxIdentifierLength63 (:27,:40), and builds each statement. Publish(:50-57) inserts onemessagesrow per subscribed queue in one statement and callspg_notifyonce per distinct queue with the queue name as payload (:57).Claim(:59-72) selects due rows (visible_after <= now()and no live lock), oldest first,LIMIT @limit FOR UPDATE SKIP LOCKED, then stampslock_token,locked_until = now() + @leaseand incrementsdelivery_count(:69).Complete,Redeliver,DeadLetterandRelease(:74-88) all matchWHERE id = @id AND lock_token = @lock_token, which is what makes a lost lease a no-op.Redeliverpushesvisible_afterout by@delayand replaces the headers (:76-79);DeadLettermoves the row in oneDELETE ... RETURNINGintoINSERT(:81-86).Renew(:90-93) extends every(id, lock_token)pair passed as arrays;NextDue(:95-97) returns seconds until the earliest claimable row.PurgeDeadLetters(:99-104) deletes, by id, up to@limitof one queue's dead letters withdead_lettered_at < now() - @retention, ordered bydead_lettered_at, over the(queue, dead_lettered_at)index (:150-154);CountDeadLetters(:106) counts one queue's dead letters.ValidateIdentifier(:177-184) throwsInvalidOperationExceptionnaming the key unless the value matches^[A-Za-z_][A-Za-z0-9_]{0,62}$(:162);Quote(:168) double-quotes it.BuildMigrate(:203-254) takes a transaction-scoped advisory lock keyed byMigrationLockKey(the first eight bytes of a SHA-256 ofmmca-broker-transport:plus the schema,:192-193,:211), creates the role if missing and grants it to the current user (:212-221), creates the schema owned by the role (:222), thenSET LOCAL ROLEso the tables and indexes are created as, and owned by, the role (:223-253).
- The constructor (
Why it's built this way: the schema and role are identifiers, which cannot be passed as parameters, so they are validated to a plain-identifier pattern and quoted, and every value is a parameter; that is the justification the store records on its CA2100 suppressions (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlMessageStore.cs:18-19). The advisory lock serializes replicas migrating the same schema at once, and owning the tables through a shared role lets each service's own database user use them once it is a member.Where it's used: constructed by
PostgreSqlBrokerTransport.Register(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:71) and handed to PostgreSqlMessageStore. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlTransportSqlTests.cs.Caveats / not-in-source: the migration only creates; nothing in source drops or alters the transport tables, so a later column change would need its own migration step.
BrokerTransportContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/BrokerTransportContext.cs:11· Level 4 · class (public sealed)
What it is: the parameter object every IBrokerTransport receives: the bound
MessageBussection, the resolved broker connection string (or null), the application configuration for any transport-specific keys, and the BrokerTopology this host consumes (BrokerTransportContext.cs:11-52).Depends on: MessageBusSettings, BrokerTopology and
Microsoft.Extensions.Configuration.IConfiguration.Concept:
[Rubric §1, SOLID]assesses whether a contract can grow without breaking its implementers. Bundling the inputs into one class keepsIBrokerTransport.Registerat two parameters, so the framework can hand transports more context (as it did withTopology) without changing a signature that adapter packages implement. The transport abstraction itself is taught at IBrokerTransport.Walkthrough
- The constructor (
BrokerTransportContext.cs:18-32) null-guardssettings,configurationandtopology(:24-26) but deliberately notconnectionString, which is nullable. Topology(:38) is the queue this host receives on and the topics bound to it; its doc notes it is also registered as a singleton so a hosted receiver can take it from DI (:34-37).Settings(:41) andConfiguration(:51) are get-only.ConnectionString(:48) is resolved, per its doc, fromMessageBus:ConnectionString, thenConnectionStrings:rabbitmq, thenConnectionStrings:messaging; null means "none is set", and the transport then keeps its own default host (:43-47).
- The constructor (
Why it's built this way: the null connection string is a meaningful value, not an error: a transport with a default host can fall back to it, while PostgreSqlBrokerTransport rejects it because a PostgreSQL broker has no default host. The context carries the value and leaves that policy to each transport.
Where it's used: built once at the end of
AddBrokerMessaging, after the topology and the receive pipeline are registered, with the connection string fromResolveBrokerConnectionString, and passed to the selected transport'sRegister(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:165-173,:293). Read by both built-in transports and by the adapter transports AzureServiceBusTransport and AmazonSqsTransport; constructed directly inMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/BrokerTransportRegistrationTests.cs.
PostgreSqlMessageStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlMessageStore.cs:16· Level 4 · class (internal sealed)
What it is: the Npgsql implementation of IPostgreSqlMessageStore: it runs the PostgreSqlTransportSql statements on an
NpgsqlDataSource, serializes headers asjsonb, and owns the once-per-process migration (PostgreSqlMessageStore.cs:16-325).Depends on: IPostgreSqlMessageStore, PostgreSqlTransportSql, PostgreSqlClaimedMessage, OutgoingBrokerMessage; Npgsql (
NpgsqlDataSource,NpgsqlDbType.Jsonb),System.Text.Json.Concept: the leased-claim contract is taught at IPostgreSqlMessageStore; this is its only production implementation.
Walkthrough
- The constructor (
PostgreSqlMessageStore.cs:31-39) takes the data source, whether it owns it, and the statements.DisposeAsyncandDisposedispose the data source only when owned (:271-286). SerializeHeadersandDeserializeHeaders(:44-51) map headers to and from a JSON object, read back with an ordinal comparer.EnsureSchemaAsync(:54-67) startsMigrateAsyncunder a lock when no attempt exists or the last one faulted or was canceled (:58-63), and returnsWaitAsync(cancellationToken)(:65), so a caller that gives up does not cancel the migration another caller awaits.MigrateAsyncruns the migration in one transaction (:289-306).PublishAsync(:84-98) binds topic, message id,jsonbheaders, body and the notify channel (:91-95).ClaimAsync(:101-133) generates one lock token for the batch (:103), reads each returned row into a PostgreSqlClaimedMessage, and sorts byIdbecauseRETURNINGorder is unspecified (:130-131).CompleteAsync,RedeliverAsync,DeadLetterAsyncandReleaseAsync(:136-173) shareSettleAsync(:308-324), which bindsidandlock_tokenand reports success as "more than zero rows affected" (:322).RenewAsync(:176-192) returns early for an empty set (:179-182) and otherwise renews all rows in one statement.PurgeDeadLettersAsync(:195-205) binds queue, retention and limit and returns the rows affected;CountDeadLettersAsync(:208-216) returns the scalar count, or 0 when the result is not along(:214).ListenAsync(:232-268) opens a dedicated connection, forwards notifications whose payload equals the queue (:239-245), issuesLISTEN, callsnotifiedonce because anything published beforeLISTENtook effect raised no notification (:253-254), then waits on the connection until canceled (:256-266).
- The constructor (
Why it's built this way: borrowing a shared data source (
ownsDataSource: false) lets a host's PostgreSQL authentication customization reach the broker connection, the migration included, while a store that created its own data source still cleans it up.Where it's used: registered as a singleton by PostgreSqlBrokerTransport through
CreateStore(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:75,:117-123) and resolved by the publisher, migrator, receiver and dead-letter sweep. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlMessageStoreTests.csand, against a real server,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.PostgreSQL.Tests/PostgreSqlLeaseRenewalTests.cs.
PostgreSqlReceiver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlReceiver.cs:27· Level 4 · class (internal sealed partial)
What it is: the PostgreSQL transport's hosted receiver: a
BackgroundServicethat claims due rows of this host's queue up to a concurrency limit, runs each through the framework IBrokerReceivePipeline, applies the returned disposition, renews leases of in-flight rows, and wakes onLISTENnotifications with polling as the fallback (PostgreSqlReceiver.cs:27-445).Depends on: BrokerTopology, IBrokerReceivePipeline, IPostgreSqlMessageStore, PostgreSqlReceiverOptions, PostgreSqlDispositionApplier, IncomingBrokerMessage.
Concept:
[Rubric §29, Resilience and Business Continuity]: every step that touches the database is wrapped so a failure is logged and retried afterRetryDelay(5 seconds,PostgreSqlReceiver.cs:39) rather than ending the service, and a row that cannot be settled is hidden for a back-off, released, or left for its lease to expire, never lost.[Rubric §10, Messaging and Integration]applies to the delivery limit: a message that crashes or hangs its consumer never reaches a pipeline decision, so without a count it would be re-claimed forever; the receiver dead-letters it instead (:29-34).Walkthrough
- Constants:
DeliveryLimitReason = "delivery-limit"(:34),RetryDelay5 seconds (:39),MinimumWait100 ms (:42),DrainTimeout10 seconds (:45). - State: a
SemaphoreSlimsized toConcurrency(:80), an in-flight map by row id (:53), and a one-slot wake channel that drops extra writes (:54). ExecuteAsync(:91-115) runsPrepareAsync, starts the listen and renew loops (:98-99), runs the receive loop, and on stop drains in-flight rows for up toDrainTimeout(:112,:417-426).PrepareAsync(:130-165) ensures the schema whenMigrateOnStartup(:136-139) and subscribes the queue to the distinct topics of the topology whenProvisionTopology(:141-147), retrying on failure (:155-163).ReceiveLoopAsync(:167-212) waits for one free slot, takes up toClaimBatchSizemore without waiting (:171-176), claims that many rows (:181), returns unused slots (:196-199), starts one task per row (:201-205), and waits for work when nothing was claimed (:207-210).UnexplainedClaims(message)(:238-246) is every claim before the current one minus the second-level redeliveries recorded in the redelivery-count header, never below zero (:240-245).ProcessAsync(:248-277) builds an IncomingBrokerMessage with the row id as its transport id (:250). WhenUnexplainedClaimshas reachedPostgreSqlReceiverOptions.MaxUnexplainedClaimsit skips the pipeline and takes theDeliveryLimitReacheddead-letter disposition; otherwise it runs the pipeline (:253-255). It applies the disposition withCancellationToken.Noneso a decided outcome is written even while the host stops (:257-259). A lost lease is logged (:261); a cancellation releases the claim (:264-267); a settle failure is logged with the back-off, counted onBrokerMetrics.SettleFailureCountertaggedtransport=postgresql, and handed toBackOffQuietlyAsync(:268-276).DeliveryLimitReached(:280-295) logs an Error, adds one toBrokerMetrics.FaultCountertagged with the event name, and returns aDeadLetterdisposition withDeliveryLimitReasonand a detail naming the claim count and the limit (:285-294).BackOffQuietlyAsync(:302-314) redelivers the row with its headers unchanged afterBrokerTransportPolicies.SettleFailureBackoff, so it spends no redelivery budget and a settle that fails every time cannot re-claim the row in a hot loop (:297-301,:306); if that write also fails the lease expires on its own (:309-313).ReleaseQuietlyAsync(:316-328) releases the claim on the same terms.WaitForWorkAsync(:329-360) sleeps until the sooner ofPollIntervaland the queue's next due row, never less thanMinimumWait(:331-347), and wakes early on a notification (:353).ListenLoopAsync(:362-386) keeps aLISTENopen and restarts it after a failure; polling keeps the queue moving meanwhile (:377).RenewLoopAsync(:388-415) renews every in-flight lease eachRenewInterval.
- Constants:
Why it's built this way: claiming only as many rows as there are free workers keeps every lease running against work that is actually executing, and notification plus polling bounds the latency of a publish to near zero while surviving a dropped listener. Settling outside the host's token avoids reprocessing a message whose handler already succeeded. Counting claims the pipeline did not explain catches the poison message that kills its host, which no handler-level retry can see.
Where it's used: registered as a hosted service by PostgreSqlBrokerTransport only when the topology has subscriptions (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:84-96). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlReceiverTests.cs.Caveats / not-in-source: the drain waits at most 10 seconds (
:45); a handler still running after that settles after the receiver is disposed, and its slot release is swallowed (:223-230). A settle-failure back-off is itself a re-claim the pipeline did not explain, so a row whose settle keeps failing is eventually dead-lettered asdelivery-limit.
IBrokerTransport
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/IBrokerTransport.cs:22· Level 5 · interface
What it is: the extension point a broker transport implements: a provider
NamethatMessageBus:Providerselects it by, the longest redelivery delay its broker can schedule, and oneRegistercall that adds its publisher and hosted receiver (IBrokerTransport.cs:22-52).Depends on: BrokerTransportContext and
Microsoft.Extensions.DependencyInjection.IServiceCollection.Concept introduced, a pluggable transport behind a name.
[Rubric §2, Design Patterns]assesses whether a variation point is expressed as a strategy rather than a switch statement, and[Rubric §32, Dependency and Supply-Chain]assesses whether optional vendor dependencies stay out of the core. The boundary is narrow by design:AddBrokerMessagingowns everything that is the same on every broker (topology, wire format, the receive pipeline with origin restore, inbox, retry, redelivery and dead-letter decisions, the outbox-only publish path, tracing), and a transport only moves bytes: it publishes an OutgoingBrokerMessage to a topic, delivers each message on the host's queue to IBrokerReceivePipeline, and carries out the BrokerDisposition the pipeline returns (:8-14). The core ships RabbitMQ and PostgreSQL; a cloud broker is an adapter package with one registration method, so the core packages never reference a vendor SDK (:17-19). Application code never sees which transport won: it publishes through IMessageBus (ADR-066, ADR-118, ADR-134).Walkthrough
Name(IBrokerTransport.cs:28) is compared case-insensitively againstMessageBus:Providerand is meant to be stable and vendor-shaped, for exampleAzureServiceBus(:24-27).MaxRedeliveryDelay(:35) is the broker's delay cap, or null for none; the receive pipeline clamps every redelivery interval to it (Amazon SQS caps a delay at 15 minutes,:30-34).Register(services, context)(:51) adds a singleton IBrokerPublisher and a hosted receiver forcontext.Topology's queue; withProvisionTopologyset, the receiver creates topics, queue and bindings idempotently before receiving and the publisher creates a missing topic on first publish (:37-43). It runs whileAddBrokerMessagingruns, so a missing namespace or connection string throws at startup rather than at the first publish (:44-47).
Why it's built this way: making the transport an instance with a name, rather than an enum the core switches on, is what lets a new broker ship without a core release, and what keeps the core free of every cloud SDK. Keeping retry and dead-letter decisions in the shared pipeline means a new transport cannot get them wrong.
Where it's used:
AddBrokerTransportrejects a blankNameand registers the instance withTryAddEnumerable(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:189-198).ResolveBrokerTransport(:199) returns a built-in forRabbitMqorPostgreSql(:201-208), otherwise a registered instance whose name matches, read off the service collection because the choice is made before any provider exists (:213); with no match it throws anInvalidOperationExceptionnaming the available providers and the remedy (:225-230).AddBrokerMessagingresolves the transport before registering anything (:82-84), passes itsMaxRedeliveryDelayto BrokerReceivePipeline (:108-115), and callsRegisterlast (:150-158). Implemented by RabbitMqBrokerTransport, PostgreSqlBrokerTransport, AzureServiceBusTransport and AmazonSqsTransport; registration behavior covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/BrokerTransportRegistrationTests.cs.Caveats / not-in-source: only
ImplementationInstanceregistrations are seen (DependencyInjection.Messaging.cs:228), so a transport registered by type or factory rather than throughAddBrokerTransportis not found.
PostgreSqlBrokerTransport
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.PostgreSql·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:39· Level 6 · class (internal sealed)
What it is: the built-in IBrokerTransport for
MessageBus:Provider = PostgreSql: topics, queues and delayed redeliveries kept in three tables of one PostgreSQL database, written on Npgsql, so any PostgreSQL (Cloud SQL, Amazon RDS, Azure Database for PostgreSQL, a container) is the broker (PostgreSqlBrokerTransport.cs:11-39).Depends on: IBrokerTransport, BrokerTransportContext, PostgreSqlTransportSettings, PostgreSqlTransportSql, PostgreSqlMessageStore, PostgreSqlPublisher, PostgreSqlSchemaMigrator, PostgreSqlReceiver, PostgreSqlReceiverOptions, MessageBusProviders, NpgsqlDataSources; Npgsql.
Concept: the transport strategy is taught at IBrokerTransport. What is particular here is
[Rubric §7, Microservices Readiness]without a broker service: a database is the broker, which is why this transport is core rather than an adapter (ADR-113, ADR-134). A publish inserts one row per subscribed queue and wakes receivers withpg_notify; a receiver claims withFOR UPDATE SKIP LOCKEDunder a renewed lease; a redelivery pushesvisible_afterout, so there is no delay cap; a dead letter moves the row to{schema}.dead_letters(:16-22).[Rubric §17, DevOps]applies to the hosted-service ordering below.Walkthrough
NamereturnsMessageBusProviders.PostgreSql(PostgreSqlBrokerTransport.cs:58);MaxRedeliveryDelayis null (:61).- A public parameterless constructor (
:44-46) and an internal one taking a function that adjusts the resolved PostgreSqlReceiverOptions, which exists only so a test can shorten the lease, renewal and poll interval (:48-55). Register(services, context)(:64-108) fails a missing connection string first (:69), reads PostgreSqlTransportSettings (:70), builds PostgreSqlTransportSql from the effective schema and role (:71), and registers the store singleton (:75) and the PostgreSqlPublisher asIBrokerPublisher(:76). WhenMigrateOnStartupholds it adds PostgreSqlSchemaMigrator (:79-82). With no subscriptions it stops there, a publish-only host (:84-87); otherwise it resolves the receiver options (:89-90), adds the PostgreSqlReceiver hosted service (:91-96), and then the PostgreSqlDeadLetterCleanupService over the host's queue withDeadLetterRetentionDays, a resolved (not required)IDistributedLockand the registeredTimeProviderorTimeProvider.System(:98-107).ReadSettings(:113-115) bindsMessageBus:PostgreSql, defaulting when the section is absent.CreateStore(:117-123) asksNpgsqlDataSources.Resolvefor a shared data source for the connection string; with one the store borrows it (:121), without one it creates and owns its own (:122).RequireConnectionString(:125-131) throws anInvalidOperationExceptiontelling the operator to setMessageBus:ConnectionString(orConnectionStrings:messaging), because unlike RabbitMQ there is no default host (:127-130).
Why it's built this way: hosted services start in registration order, so registering the migrator before the receiver guarantees the schema exists before the first claim (
:78). The dead-letter sweep is registered only on a consuming host, so each service purges and gauges its own queue's dead letters (:29-31). Resolving a shared data source means a host that registers anINpgsqlDataSourceConfigurator(an RDS, Cloud SQL or Entra token provider) runs the transport, migration included, on the same authenticatedNpgsqlDataSourceits PostgreSQL contexts use (:33-37).Where it's used: instantiated by
ResolveBrokerTransportwhen the provider isPostgreSql(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:221-223). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransportTests.csand, against a real server,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.PostgreSQL.Tests/PostgreSqlBrokerTransportTests.cs.Caveats / not-in-source: the startup migration needs rights to create a role and a schema; a host without them sets
MigrateOnStartupto false and relies on another host or a deployment step to run the idempotent DDL (see PostgreSqlTransportSettings). BecauseMaxRedeliveryDelayis null (:61), every configured redelivery interval runs unclamped.
IRabbitMqOperations
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/IRabbitMqOperations.cs:9· Level 0 · interface (internal)
What it is: the five broker calls the RabbitMQ transport makes outside its consume loop: declare a fanout exchange, declare a queue, check a queue exists, bind a queue to an exchange, and publish a confirmed message (
IRabbitMqOperations.cs:9-55). The interface doc names RabbitMqChannelOperations as its one real implementation (IRabbitMqOperations.cs:3-8).Depends on: nothing first-party. The signatures use BCL types only (
IDictionary<string, object?>for declaration arguments,ReadOnlyMemory<byte>for the body,IReadOnlyDictionary<string, string>for headers), so the RabbitMQ.Client types stay behind the implementation.Concept introduced, a test boundary around a broker client.
[Rubric §14, Testability]assesses whether the logic worth testing can run without its infrastructure. The naming, provisioning and disposition rules of this transport are pure decisions about which entity to declare and which queue a copy goes to; the interface doc says it exists so those rules are "testable without a broker" (IRabbitMqOperations.cs:4-6). RabbitMqProvisioner, RabbitMqDispositionApplier and RabbitMqPublisher take this interface rather than a channel, and the test project supplies a recording fake (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RecordingRabbitMqOperations.cs). The consume loop itself is not behind it: RabbitMqReceiver talks to its consume channel directly.Walkthrough
DeclareFanoutExchangeAsync(exchange)(IRabbitMqOperations.cs:15): durable fanout exchange, idempotent.DeclareQueueAsync(queue, arguments)(:22): durable queue, idempotent for identical arguments.EnsureQueueExistsAsync(queue)(:28): a passive declaration that throws when the queue is missing.BindQueueAsync(queue, exchange)(:35): binds a queue to a fanout exchange.PublishAsync(exchange, routingKey, mandatory, body, headers)(:48-54): a persistent publish that completes only on the broker's confirm, throwing on a nack or, withmandatory, on an unroutable message (:37-39).""is the default exchange, where the routing key is a queue name (:41-42).
Why it's built this way: every operation the transport needs before acknowledging a delivery is a confirmed, awaited call, so a fake that records the calls is enough to prove the ordering and the arguments.
Where it's used: implemented by RabbitMqChannelOperations; consumed by RabbitMqProvisioner, RabbitMqPublisher and RabbitMqDispositionApplier.
NativePushPayloads
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Push·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/NativePushPayloads.cs:13· Level 0 · class (public static)
What it is: the pure helper that builds the two platform-native JSON payloads for OS-level push: the FCM v1 message for Android and the APNs alert for iOS (
NativePushPayloads.cs:13-68). It holds no state and references no vendor SDK, which is why the payload shapes can be asserted in a unit test and shared by every cloud adapter.Depends on:
System.Text.Jsonfor serialization. No first-party service types at all.Concept introduced, the third notification channel's wire contract.
[Rubric §9, API and Contract Design]assesses whether the shape of a message crossing a boundary is defined in one place rather than assembled ad hoc at each call site, and[Rubric §14, Testability]assesses whether the parts worth testing can be tested without their infrastructure. The framework already carries a durable per-user notification inbox and a transient SignalR push; native OS-level delivery (ADR-044) is the third, and it is the only one whose payload is dictated by an external vendor. FCM v1 wants amessageenvelope with anotificationblock; APNs wants a reservedapsblock with analertinside it and any application data as sibling top-level keys. The class doc (NativePushPayloads.cs:5-12) records how the adapters share that contract: Azure Notification Hubs forwards these payloads verbatim, SNS mobile push wraps them in its per-platform message structure, and the FCM adapter maps the same fields onto FirebaseAdmin's typed message with a test pinning the equivalence, so one notification looks the same on a device whichever cloud delivered it.[Rubric §32, Dependency and Supply-Chain]applies through the same doc: the helper is pureSystem.Text.Json, so the core package stays free of any push vendor SDK (ADR-134).Walkthrough
BuildFcmV1Payload(title, body, metadata)(NativePushPayloads.cs:20-35) guardstitleandbodyagainst null (:22-23), buildsnotificationfrom them (:25-28), attachesdataonly when the metadata dictionary is non-empty (:29-32), and serializes the whole thing under amessageroot (:34).BuildApnsPayload(title, body, metadata)(NativePushPayloads.cs:42-67) applies the same null guards (:44-45), builds theaps.alertblock (:47-53), then lifts each metadata pair to a top-level custom key, which is where APNs expects application data. The guard at:58-62is the interesting line: a metadata key literally namedapsis skipped, because writing it would clobber the alert block and produce a notification the device shows as nothing.- User tags and audience chunking are not here. Those are Azure Notification Hubs concepts and live in the Azure adapter's NativePushUserTags.
Why it's built this way: keeping this pure and public means the vendor payload shapes are covered by fast tests that need no notification hub, no credentials and no network, and every adapter package composes against one definition instead of carrying its own copy.
Where it's used: AzureNotificationHubNativePushSender calls both builders for user-targeted sends (
MMCA.Common/Source/Hosting/MMCA.Common.Azure/Notifications/AzureNotificationHubNativePushSender.cs:35-36) and for broadcasts (:37-38); SnsPushMessage calls both to fill its per-platform structure (MMCA.Common/Source/Hosting/MMCA.Common.Aws/Notifications/SnsPushMessage.cs:29-30). FcmPushMessage references the type without calling it, as the class doc describes. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Notifications/Push/NativePushPayloadsTests.cs, with the FCM equivalence inMMCA.Common/Tests/Hosting/MMCA.Common.Gcp.Tests/Notifications/FcmNativePushSenderTests.cs.Caveats / not-in-source: the helper takes no options, so a host wanting a different payload shape replaces INativePushSender rather than configuring this.
RabbitMqConnectionSecurityNoticeService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqConnectionSecurityNoticeService.cs:16· Level 0 · class (internal sealed partial)
What it is: a hosted service that writes one startup Warning when the RabbitMQ transport connects with the broker's default
guest/guestcredentials or over cleartextamqp://, in a host that is not Development (RabbitMqConnectionSecurityNoticeService.cs:6-12,:16-79). It warns and does not refuse: the connection is still made as configured (:10-11).Depends on:
IHostedService, an optionalIHostEnvironmentand anILogger(RabbitMqConnectionSecurityNoticeService.cs:16-19); source-generated[LoggerMessage]logging (:75-78). No first-party types: the findings string is computed by its own staticDescribeand passed in.Concept introduced, a startup notice for an insecure broker connection.
[Rubric §11, Security]assesses whether insecure defaults are visible before they reach production. A RabbitMQ transport with no connection string falls back to the client defaultamqp://guest:guest@localhost:5672, which is the right zero-configuration choice for the Aspire development stack and the wrong one anywhere else. Rather than fail startup (which would also break a deliberate non-Development test host), the transport registers this service only whenDescribefinds something weak, and the service logs once per start when the environment is not Development. A host with no registeredIHostEnvironmentreads as production, so the notice fires (:9-10,:27-30).[Rubric §13, Observability & Operability]applies to the shape of the signal: one Warning naming the setting to change (ConnectionStringSetting = "MessageBus:ConnectionString",:22), the findings and the environment name, with the fix in the message text (:77).Walkthrough
- Constructor (
RabbitMqConnectionSecurityNoticeService.cs:16-19): a primary constructor taking the pre-phrasedfindings, the nullableIHostEnvironmentand the logger. StartAsync(:25-33): whenenvironment?.IsDevelopment()is nottrue(:27), callsLogInsecureConnectionwith the setting name, the findings and the environment name, or"(none registered)"when there is no environment (:29).StopAsync(:36) does nothing.Describe(uri)(:46-58): a null URI counts as both default credentials and cleartext, since it connects toamqp://localhost:5672withguest/guest(:48-49). Otherwise default credentials come fromUsesDefaultCredentials(uri.UserInfo)and cleartext from a case-insensitiveamqpscheme. The tuple switch (:51-57) returns one of three phrases ("uses the default guest/guest credentials over cleartext amqp://", "uses the default guest/guest credentials", "uses cleartext amqp://") ornullwhen there is nothing to report.UsesDefaultCredentials(userInfo)(:60-73): empty user info means the client default, sotrue(:62-65). Otherwise it splits on the first:and URI-unescapes user and password (:67-69), and matches only userguestwith an empty password or passwordguest, both ordinal (:71-72).LogInsecureConnection(:75-78): aLogLevel.Warningmessage stating thatMessageBus:Provideris RabbitMq, naming the setting and the findings, the environment, and the remedy (anamqps://URI with credentials of its own).
- Constructor (
Why it's built this way: the decision is split in two on purpose. Whether the connection is weak is known at registration from the parsed URI, so the transport registers nothing when an
amqps://URI with its own credentials is configured; whether the host is Development is known only once the container is built, so the environment check runs at start. A Warning rather than an exception keeps development and test hosts working while making the production case loud.Where it's used: registered by RabbitMqBrokerTransport
Registeras a hosted service only whenDescribereturns findings (RabbitMqBrokerTransport.cs:43-53). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RabbitMqConnectionSecurityNoticeTests.cs:23.Caveats / not-in-source: the check reads only the configured URI and never probes the broker, so an
amqps://URI with non-default credentials passes regardless of what the broker itself enforces.
RabbitMqConnectionSource
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqConnectionSource.cs:11· Level 0 · class (internal sealed)
What it is: one lazily opened RabbitMQ connection with automatic recovery (
RabbitMqConnectionSource.cs:11-115). The publisher and the receiver each own one, so a publisher held up by broker flow control never stalls the consumer's acknowledgements (RabbitMqConnectionSource.cs:5-9).Depends on: RabbitMQ.Client's
ConnectionFactoryandIConnection; aSemaphoreSlim(:14).Concept introduced, deferred connection opening.
[Rubric §13, Observability & Operability]assesses how a service behaves when a dependency is down. Opening is deferred to the first use, so a host whose broker is unreachable still starts and the outbox keeps what it cannot publish; a failed open is not cached, so the next call tries again (RabbitMqConnectionSource.cs:5-7). Recovery after the connection exists is delegated to the client.Walkthrough
- The constructor (
RabbitMqConnectionSource.cs:21-22) only builds the factory; nothing touches the network. CreateFactory(:31-47) turns onAutomaticRecoveryEnabledandTopologyRecoveryEnabledwith a 5-secondNetworkRecoveryInterval(:35-37), sets theClientProvidedNameshown in the management UI, and applies the URI only when one is given (:41-44); with none the client's defaultamqp://guest:guest@localhost:5672applies (:19).GetConnectionAsync(:52-72) returns the cached connection without locking (:56-59), otherwise takes the gate (:61) and opens with??=(:65), so concurrent first callers share one open. An exception escapes before assignment, which is why a failed open is retried.DisposeAsync(:75-98) closes with a handshake and swallows a close failure on a connection the broker already dropped (:87-92); the synchronousDispose(:104-114) drops the connection without the handshake. Both are idempotent through_disposed.
- The constructor (
Why it's built this way: one connection per role isolates publishing from consuming, and automatic topology recovery means a broker restart re-opens the connection, its channels and the consumer without transport code (
:24-26).Where it's used: RabbitMqBrokerTransport creates one named
{queue} (publish)for the publisher and one named{queue} (receive)for the receiver (RabbitMqBrokerTransport.cs:56,:56); RabbitMqChannelOperations and RabbitMqReceiver open channels on it.
RabbitMqHeaders
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqHeaders.cs:11· Level 0 · class (internal static)
What it is: the converter between the framework's string-to-string headers and AMQP header tables (
RabbitMqHeaders.cs:11-72).Depends on: BCL only (
Encoding.UTF8,CultureInfo.InvariantCulture). The keys it carries are defined by BrokerHeaders.Concept: the transport-neutral header contract is taught at BrokerHeaders; this is the RabbitMQ encoding of it.
Walkthrough
Encode(RabbitMqHeaders.cs:19-30) copies every pair into an ordinal dictionary as a string value (:24-27). Every value goes over the wire as an AMQP long string (:5-8).Decode(:40-71) is the reverse, and is wider because the client hands a long string back as UTF-8 bytes. Byte arrays decode as UTF-8, strings pass through, booleans become"true"/"false", otherIFormattablevalues format invariantly, and anything else is dropped (:55-62). A key with thex-prefix (:14) is skipped (:50-53): those are headers RabbitMQ stamps itself, such as thex-deathtable a delay queue adds, so a redelivered copy never accumulates them (:33-36).
Why it's built this way: dropping broker headers on read matters because RabbitMqDispositionApplier republishes a copy built from the decoded headers; without the filter each trip through a delay queue would carry a growing
x-deathhistory.Where it's used:
Encodeby RabbitMqChannelOperations (RabbitMqChannelOperations.cs:67);Decodeby RabbitMqReceiver (RabbitMqReceiver.cs:210). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RabbitMqHeadersTests.cs.
PushNotificationSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Push·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:8· Level 1 · class (sealed)
What it is: the
PushNotificationssection: the on switch, the SignalR hub path, the regular expression a channel key must match before a client may join or leave a channel, the per-user cap on simultaneous hub connections, the per-connection bounds on channel memberships and join attempts, and the token-expiry cut-off (PushNotificationSettings.cs:8-101).Depends on:
NotificationScopeKeyfromMMCA.Common.Shared.Notifications(:1), for thePatternconstant that supplies the default. See NotificationScopeKey. No externals beyond four[Range]data annotations, onMaxConnectionsPerUser(PushNotificationSettings.cs:49),MaxChannelsPerConnection(:62),ChannelJoinsPerMinute(:75) andChannelJoinBurst(:84), which are whatValidateDataAnnotations()checks at startup. TheChannelJoinsPerMinuteremarks name IChannelJoinAuthorizer (:70) as the cost the limit protects.Concept introduced: allow-listing client-supplied group names.
[Rubric §11, Security]and[Rubric §26, Front-End Security]both apply. A hub method that takes a channel key and callsGroups.AddToGroupAsyncis joining a SignalR group named by the CLIENT. With no constraint, a caller could join any group the server publishes to and receive another event's or another session's traffic.ChannelKeyPatternis that constraint (PushNotificationSettings.cs:27-37).[Rubric §15, Best Practices & Code Quality]shows up in where the default comes from. The property does not hard-code a regex: it defaults toNotificationScopeKey.Pattern(PushNotificationSettings.cs:37, the constant"^(event|session):[0-9]+\z"atNotificationScopeKey.cs:36), the SAME constant the producersNotificationScopeKey.ForEventandForSessionformat against (NotificationScopeKey.cs:48,:54). Producer and guard therefore cannot drift apart by editing one of them; a host that overrides the pattern from configuration takes that alignment on itself, which the doc says outright (PushNotificationSettings.cs:33-34).[Rubric §11, Security]also coversMaxConnectionsPerUser: an[Authorize]hub without a connection cap lets one authenticated user open unbounded WebSockets and exhaust the replica, denying live notifications to everyone else (PushNotificationSettings.cs:39-50).0opts a host back out of the cap entirely. The same reasoning bounds what one connection may do once open:MaxChannelsPerConnectioncaps the SignalR group memberships it holds on the replica and the backplane (:52-63), andChannelJoinsPerMinutewithChannelJoinBurstrate-limits its join attempts, refused ones included, because each well-formed join consults the host's entitlement check, which may call another service (:65-85).Walkthrough: one static field and eight
initproperties.SectionName = "PushNotifications"(PushNotificationSettings.cs:11).Enabled(:14): plainbool, defaultfalse.HubPath(:25): defaults to"/hubs/notifications". Its doc comment (:16-24) carries two couplings. The JWT bearer handlers accept the query-stringaccess_tokenon this path (and under/hubs), and a host that moves the hub elsewhere must also setRateLimiting:HubPathPrefixes, which the rate limiter reads separately. And the shipped client,NotificationHubServicein MMCA.Common.UI, connects at the default/hubs/notificationswith no setting to follow a move, so changing this path also means changing the client, the gateway route,RateLimiting:HubPathPrefixesand the same-origin proxy exemption.ChannelKeyPattern(:37). Enforcement lives in NotificationHub:EnsureValidChannelKey(NotificationHub.cs:229) pulls aRegexout of a staticConcurrentDictionarycache keyed on the pattern string (:232-233, the cache declared at:62) and throwsHubException("Invalid channel key.")on a non-matching key (:237); bothJoinChannelAsync(:154) andLeaveChannelAsync(:187) call it before touchingGroups. The compiled regex carries a one-second match timeout (NotificationHub.cs:59,:233), so a pathological configured pattern cannot hang the connection, and the cache means join and leave do not recompile per call.MaxConnectionsPerUser(:50):[Range(0, 10_000)](:49), default20;0disables the cap (PushNotificationSettings.cs:39-42). Tagged SEC-ADC-25 in the remarks: the hub is[Authorize]but had noOnConnectedAsyncoverride, so a single valid user token could open unbounded WebSockets and exhaust the replica, stopping live notifications for everyone (:43-48).MaxChannelsPerConnection(:63):[Range(0, 1_000)](:62), default32;0disables the cap. It counts joins minus leaves, and a repeated join of a channel already held does not take a second slot (:52-56). The default sits well above what a client shows at once, an event and the sessions on screen (:57-61).ChannelJoinsPerMinute(:76):[Range(0, 10_000)](:75), default60;0disables the limit. A token bucket per connection, refilled at this rate once the burst is spent, with refused joins counted (:65-74).ChannelJoinBurst(:85):[Range(1, 1_000)](:84), default32, the attempts a connection may make at once beforeChannelJoinsPerMinuteapplies. A reconnect opens a new connection with a full burst, so the default matchesMaxChannelsPerConnectionand a client can re-join every channel it held without being throttled (:78-83).CloseConnectionsOnTokenExpiry(:100): plainbool, defaultfalse(:86-89). A hub connection is authenticated once, when it opens, so without this a user who is locked, loses a role or signs out everywhere keeps receiving pushes until the connection drops. With it on, the connection ends with its access token; the shipped client reconnects with a fresh token, so a signed-in user sees one reconnect per token lifetime and a revoked user is refused. The cut-off is bounded byJwt:AccessTokenExpirationMinutes, not immediate, and it needs no sticky ingress because each replica enforces it on the connections it holds (:90-99).[Rubric §11, Security]applies: this is the setting that bounds how long a revoked identity keeps a live channel.
Why it's built this way: a configurable pattern rather than a hard-coded one lets each application define its own channel taxonomy without forking the hub, while the shipped default is restrictive rather than permissive. Sourcing that default from the producer's own constant is the cheaper half of the same idea: the safe configuration is also the zero-configuration one.
Where it's used: bound with
.ValidateDataAnnotations().ValidateOnStart()inAddPushNotifications(MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:64-67), which then registers SignalR (:69), adds the Redis backplane when aredisconnection string is present (:71-72,:81), and replaces the null implementations with SignalRPushNotificationSender and SignalRLiveChannelPublisher (:97-98). The settings object itself is injected asIOptions<PushNotificationSettings>(NotificationHub.cs:36) and read by NotificationHub in three places.EnsureValidChannelKeyreadsChannelKeyPattern(:232).OnConnectedAsync(:76) readsMaxConnectionsPerUserintocap(:78), tracks a staticConnectionsPerUsercount keyed byContext.UserIdentifier(:73), and throwsHubException("Too many concurrent connections for this account.")when a new connection would push the count overcap(:84-90); the rejected connection's slot is given back immediately so an aborted connection cannot lock the user out once it drains (:86-88). The cap is skipped whencap <= 0or the identifier is empty (:81).JoinChannelAsync(:143) spends a join from the per-connection ConnectionChannels token bucket before the shape check, refusing with "Too many channel joins; try again shortly." (:148-152), then reserves a membership slot againstMaxChannelsPerConnectionbefore the entitlement check, refusing with "Too many channels joined on this connection." (:156-161) and releasing the slot if the join does not complete (:173-177). The bucket starts full atChannelJoinBurstand refills atChannelJoinsPerMinute(NotificationHub.cs:256-285).MapNotificationHubreads the settings to map the hub atHubPathonly whenEnabledis true, and passesCloseConnectionsOnTokenExpiryto SignalR'sCloseOnAuthenticationExpiration(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/SignalRExtensions.cs:24-33). The default pattern is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Settings/PushNotificationSettingsTests.cs:15-16and an override by:26,:31; the connection cap itself is covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Hubs/NotificationHubConnectionCapTests.cs, and the channel bounds, including the defaults letting a reconnect re-join every held channel, byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Hubs/NotificationHubChannelBoundsTests.cs:71-213.Caveats: this class stands alone. There is no
IPushNotificationSettingsabstraction in the current source, so a consumer that wants the values takes the concrete options type.
RabbitMqChannelOperations
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqChannelOperations.cs:12· Level 1 · class (internal sealed)
What it is: the real IRabbitMqOperations: one channel with publisher confirms on a RabbitMqConnectionSource, with every call serialized on that channel (
RabbitMqChannelOperations.cs:12-171).Depends on: IRabbitMqOperations, RabbitMqConnectionSource, RabbitMqHeaders, BrokerHeaders; RabbitMQ.Client's
IChannel,BasicPropertiesandCreateChannelOptions.Concept introduced, publisher confirms.
[Rubric §10, Messaging & Integration]assesses whether a message is known to be durable before the sender forgets it. A plain AMQP publish returns as soon as the bytes leave the client; a confirmed publish completes only when the broker has taken responsibility for the message. The channel is created with bothpublisherConfirmationsEnabledandpublisherConfirmationTrackingEnabled(RabbitMqChannelOperations.cs:166-168), which makesBasicPublishAsyncawait the broker's ack and throw on a nack or a mandatory return (:5-10). That is what lets the outbox delete a row and the receiver acknowledge an original only after its copy is safe.Walkthrough
- Fields (
RabbitMqChannelOperations.cs:14-18): the connection source, whether this instance owns it, aSemaphoreSlim(1, 1)gate and the current channel. The constructor (:23-29) takesownsConnections, which decides whether disposal cascades to the connection. - The four declaration methods (
:32-50) map one-to-one onto the client: a durable, non-auto-delete fanout exchange (:34), a durable, non-exclusive queue with the caller's arguments (:40),QueueDeclarePassiveAsyncfor the existence check (:45) and a binding with an empty routing key (:50). PublishAsync(:54-75) buildsBasicPropertieswithPersistent = true, the encoded header table, andContentTypeandMessageIdlifted from the framework headers when present (:64-70).RunAsync(:134-148) takes the gate, gets a channel and runs the operation, so calls never interleave on one channel.GetChannelAsync(:150-170) reuses an open channel (:152-155); a channel that exists but is closed was closed by the broker (a failed passive declaration or conflicting arguments does that), which automatic recovery does not repair, so it is discarded and replaced (:157-163).DisposeAsync(:78-97) closes the channel quietly (CloseQuietlyAsync,:117-132) and disposes the connection only when owned (:91-94);Dispose(:100-115) is the synchronous twin.
- Fields (
Why it's built this way: serializing calls on one confirmed channel keeps the confirm bookkeeping simple and the ordering of declarations deterministic; replacing a broker-closed channel on the next call turns a channel-level error into one failed operation rather than a dead publisher.
Where it's used: RabbitMqBrokerTransport wraps the publisher's connection in one that owns it (
RabbitMqBrokerTransport.cs:56); RabbitMqReceiver creates one that does not own its connection, for declarations and disposition copies (RabbitMqReceiver.cs:70).
NullNativePushSender
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Push·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/NullNativePushSender.cs:12· Level 3 · class (public sealed)
What it is: the inert default for INativePushSender. Its one member,
SendToUsersAsync, returns NativePushOutcome.Noneand does nothing else (NullNativePushSender.cs:12-17).Depends on: INativePushSender and NativePushOutcome.
Concept introduced, the null-object default for an optional channel.
[Rubric §1, SOLID]assesses whether callers depend on abstractions rather than on the presence of a configured backend, and[Rubric §15, Best Practices & Code Quality]assesses whether the "not configured" case costs conditional code at every call site. The alternative to this class is anINativePushSender?that every handler null-checks, or a host that throws at resolution time when no hub is configured. Both push a deployment concern into application code. Registering a do-nothing implementation as the default means the third channel always resolves, the send handler is written once with no branch, and enabling native push in an environment is purely a configuration change. The same posture appears in NullFileStorageService, NullPushDeviceRegistrar, and, outside this group, NullPushNotificationSender.Walkthrough:
SendToUsersAsync(NullNativePushSender.cs:15-16) is an expression-bodiedTask.FromResult(NativePushOutcome.None), the outcome of a call that attempted nothing (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/NativePushOutcome.cs:11-12). Returning an outcome rather thanTask.CompletedTaskkeeps the caller's bookkeeping uniform: SendPushNotificationHandler records the per-platform outcome on the notification row, and null counts there mean "not attempted" (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationHandler.cs:136-141). There is no logging, deliberately: a per-notification "push was skipped" line in a host that never intends to enable the channel is noise, not signal.Why it's built this way: ADR-044 records that the framework pipeline ships inert by default and each consumer switches it on through a vendor adapter. This class is that decision expressed in code, and the DI comment above its registration names the three adapters that replace it (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:421-424).Where it's used: registered by
AddInfrastructurethroughTryAddTransient(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:425), immediately alongside NullPushDeviceRegistrar (:413). Each adapter uses plainAddTransientfor its pair, so the later registration wins:AddAzureNotificationHubsPush(MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:135-136),AddAmazonSnsPush(MMCA.Common/Source/Hosting/MMCA.Common.Aws/AwsServiceCollectionExtensions.cs:194-195) andAddFirebaseCloudMessagingPush(MMCA.Common/Source/Hosting/MMCA.Common.Gcp/GcpServiceCollectionExtensions.cs:166-167). CloudAdapterTripwire also tests for this type: it treats a resolvedNullNativePushSenderas "no push adapter registered" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwire.cs:78).Caveats / not-in-source: because the swap is "last registration wins" rather than a removal, both descriptors remain in the collection when native push is enabled. Anything resolving
IEnumerable<INativePushSender>would see the no-op as well as the real sender; no first-party code does.
RabbitMqNames
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqNames.cs:19· Level 3 · class (internal static)
What it is: the RabbitMQ entity names and declaration arguments derived from the BrokerTopology (
RabbitMqNames.cs:19-76): one durable fanout exchange per topic, the host's durable queue,{queue}-errorfor dead letters and{queue}-delay-{seconds}sper redelivery interval (RabbitMqNames.cs:5-17).Depends on: BrokerNaming (
Fit), BrokerTopology; BCL only otherwise.Concept introduced, delayed redelivery without a plugin.
[Rubric §10, Messaging & Integration]assesses whether retry and poison handling are designed rather than left to the broker's defaults. RabbitMQ has no native delayed delivery; the usual answer is therabbitmq_delayed_message_exchangeplugin. This transport instead declares one queue per delay interval whosex-message-ttlexpires every message after the interval and dead-letters it through the default exchange ("") back to the host queue (RabbitMqNames.cs:70-75). Because every message in one delay queue has the same time to live, expiry at the head keeps them in order, and because the arguments are a pure function of the name, every host declares the queue identically and a repeated declaration is a no-op (:60-66).Walkthrough
MaxNameLength = 255(RabbitMqNames.cs:22), RabbitMQ's short-string limit; every name passes throughBrokerNaming.Fitwith it, so a publisher and a consumer in different hosts compute the same entity (:5-7).DeadLetterReasonHeaderandDeadLetterDetailHeader(:25,:28):x-mmca-dead-letter-reasonandx-mmca-dead-letter-detail.Exchange(topic),Queue(queueName)andErrorQueue(queueName)(:33,:38,:43).DelaySeconds(delay)(:51) rounds up to whole seconds with a floor of one, so a sub-second delay still goes through a delay queue rather than straight back to the host queue.DelayQueue(queueName, delaySeconds)(:57-58) andDelayQueueArguments(:70-75): TTLdelaySeconds * 1000, dead-letter exchange"", dead-letter routing key the fitted host queue name.
Caveats / not-in-source: the dead-letter headers start with
x-, the prefix RabbitMqHeaders drops on read, so a dead-lettered copy read back by a receiver would not surface them as framework headers; they are meant for an operator inspecting the error queue.Where it's used: RabbitMqProvisioner, RabbitMqDispositionApplier, RabbitMqPublisher and RabbitMqReceiver. Covered by
MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RabbitMqNamesTests.cs.
NullPushDeviceRegistrar
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications.Push·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/NullPushDeviceRegistrar.cs:14· Level 4 · class (public sealed)
What it is: the inert default for IPushDeviceRegistrar. It accepts and discards registrations so a client can call the Devices endpoints unconditionally; nothing is stored until a host enables native push (
NullPushDeviceRegistrar.cs:14-27).Depends on: IPushDeviceRegistrar, DeviceInstallationRequest, and Result.
Concept: the null-object default introduced at NullNativePushSender. Here all three operations return success (
NullPushDeviceRegistrar.cs:17-18,:21-22,:25-26), which is the right choice for this contract specifically: a mobile client registers its device at startup as a matter of course, and failing that call in a host without a hub would surface as an error in an app whose user did nothing wrong.[Rubric §9, API and Contract Design]applies: the Devices endpoints keep the same response shape whether or not the channel is enabled, so no client needs a capability check.Walkthrough:
UpsertAsync(NullPushDeviceRegistrar.cs:17-18),DeleteAsync(:21-22) andDeleteAllForUserAsync(:25-26) are all expression-bodiedTask.FromResult(Result.Success()).DeleteAllForUserAsyncis the account-deletion path: DeleteUserPushInstallationsInternalCommandHandler calls it (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserPushInstallationsInternalCommandHandler.cs:31), and with no adapter there is nothing stored to remove, so success is the truthful answer. There is no validation of the platform string here, unlike AzureNotificationHubDeviceRegistrar, so a request that the real registrar would reject as an unsupported platform is accepted by this one.Why it's built this way: ADR-044 ships the pipeline inert, and both halves of the channel (the sender and the registrar) have to be inert together, which is why they are registered as a pair (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:425-426) and replaced as a pair by each vendor adapter (for exampleMMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:135-136).Where it's used: registered by
AddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:426) and resolved by DevicesController (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/DevicesController.cs:27) in any host that has not registered a push adapter (AddAzureNotificationHubsPush,AddAmazonSnsPushorAddFirebaseCloudMessagingPush) with an enabled section.Caveats / not-in-source: the divergence in validation strictness between this and the real registrar means a test running against the default registration cannot catch an invalid
Platformvalue. That behavior is only exercised through AzureNotificationHubDeviceRegistrar.
RabbitMqProvisioner
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqProvisioner.cs:16· Level 4 · class (internal sealed)
What it is: the part of the transport that creates RabbitMQ entities, once per process and idempotently, honoring
MessageBusSettings.ProvisionTopology(RabbitMqProvisioner.cs:16-136).Depends on: IRabbitMqOperations, RabbitMqNames, BrokerTopology, MessageBusSettings;
ConcurrentDictionary.Concept introduced, provisioning on or off.
[Rubric §17, DevOps]assesses whether infrastructure ownership is explicit. With provisioning on, every entity is declared, and a repeated declaration with the same arguments is a no-op on the broker. With it off, nothing is declared: the host queue, its error queue and every delay queue must already exist, and the receive side checks the queue it is about to publish a copy to passively, so a missing one fails the disposition (and the message is redelivered) instead of the copy being silently dropped as unroutable (RabbitMqProvisioner.cs:5-12).Walkthrough
- Two ordinal
ConcurrentDictionarysets remember declared exchanges and queues (RabbitMqProvisioner.cs:18-19);ProvisionTopology(:22) comes from the primary constructor. ProvisionReceiveAsync(:32-56) returns at once when provisioning is off (:37-40), otherwise declares the host queue (:42-43), its error queue (:45-47), and for each subscription the topic's fanout exchange plus the binding to the queue (:49-55).EnsureExchangeAsync(:63-74) declares a topic's exchange before its first publish, skipping it when provisioning is off or already declared (:67);ForgetExchange(:81) drops it from the set after a failed publish, so the next publish declares it again in case it was deleted out of band.EnsureErrorQueueAsync(:88-93) andEnsureDelayQueueAsync(:104-110) funnel intoEnsureQueueAsync(:112-135), which declares with arguments when provisioning and otherwise calls the passiveEnsureQueueExistsAsync(:125-132), then caches the name (:134). Delay queues are therefore declared lazily, the first time an interval is used.
- Two ordinal
Why it's built this way: a host that runs with least-privilege broker credentials cannot declare entities, so provisioning has to be switchable; the passive check is what keeps that mode from losing messages.
Where it's used: RabbitMqBrokerTransport creates one for the publisher and one for the receiver (
RabbitMqBrokerTransport.cs:57,:57); consumed by RabbitMqPublisher, RabbitMqReceiver and RabbitMqDispositionApplier. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RabbitMqProvisionerTests.cs.
RabbitMqDispositionApplier
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqDispositionApplier.cs:21· Level 5 · class (internal static)
What it is: the step that carries out a BrokerDisposition for a delivered message, up to but not including the acknowledgement of the original, which the receiver sends once this returns (
RabbitMqDispositionApplier.cs:21-74).Depends on: IRabbitMqOperations, RabbitMqProvisioner, RabbitMqNames, IncomingBrokerMessage, BrokerDisposition with Redeliver, DeadLetter and Completed, BrokerHeaders.
Concept: the disposition model is taught at BrokerDisposition; this is how RabbitMQ realizes it.
[Rubric §10, Messaging & Integration]applies to the ordering: both copies are published mandatory and confirmed, so the original is acknowledged only once its copy is safely in a queue, and a failure here throws so the receiver returns the original to the queue (RabbitMqDispositionApplier.cs:16-17).Walkthrough:
ApplyAsync(RabbitMqDispositionApplier.cs:31-73).Redeliver(:44-54): ensure the delay queue forRabbitMqNames.DelaySeconds(redeliver.Delay)(:46-48), copy the headers with the newBrokerHeaders.RedeliveryCount(:49-52), and publish to the delay queue through the default exchange, mandatory (:53).DeadLetter(:56-69): ensure the error queue (:58), add the reason header and, when present, the detail header (:59-66), and publish to{queue}-error, mandatory (:68).Completed: nothing to publish; the acknowledgement is all there is (:72).
Where it's used: called by RabbitMqReceiver for every processed delivery (
RabbitMqReceiver.cs:216). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RabbitMqDispositionApplierTests.cs.
RabbitMqPublisher
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqPublisher.cs:10· Level 5 · class (internal sealed)
What it is: the RabbitMQ IBrokerPublisher: it publishes each message, persistent and confirmed, to its topic's fanout exchange, declaring the exchange first when provisioning. A publish the broker did not confirm throws, so the outbox keeps the row and retries it (
RabbitMqPublisher.cs:3-8).Depends on: IBrokerPublisher, OutgoingBrokerMessage, IRabbitMqOperations, RabbitMqProvisioner, RabbitMqNames.
Concept: the publisher contract is taught at IBrokerPublisher.
Walkthrough
- The constructor (
RabbitMqPublisher.cs:18-25) takes the operations and the provisioner. PublishAsync(:28-47) maps the topic to its exchange (:32), ensures the exchange (:35), and publishes withmandatory: falseand an empty routing key (:39-40): a fanout exchange with no queue bound yet means no host consumes the event, which is not an error for the publisher (:37-38). Any failure makes the provisioner forget the exchange before rethrowing (:42-46).DisposeAsyncandDispose(:50-51,:54) forward to the operations when they are disposable.
- The constructor (
Where it's used: registered as the singleton
IBrokerPublisherby RabbitMqBrokerTransport (RabbitMqBrokerTransport.cs:55-57). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RabbitMqPublisherTests.cs.
RabbitMqReceiver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqReceiver.cs:22· Level 6 · class (internal sealed partial)
What it is: the hosted service that consumes the host queue with manual acknowledgements, hands every delivery to IBrokerReceivePipeline and applies the resulting disposition before acknowledging (
RabbitMqReceiver.cs:22-286).Depends on:
BackgroundService, BrokerTopology, IBrokerReceivePipeline, RabbitMqConnectionSource, RabbitMqChannelOperations, RabbitMqProvisioner, RabbitMqDispositionApplier, RabbitMqHeaders, RabbitMqNames, IncomingBrokerMessage, BrokerTransportPolicies (SettleFailureBackoff), BrokerMetrics (SettleFailureCounter); RabbitMQ.Client'sAsyncEventingBasicConsumer; source-generated[LoggerMessage]logging.Concept introduced, a receiver that never stops the host.
[Rubric §13, Observability & Operability]assesses whether a service degrades and recovers rather than crashes. When the broker is unreachable at startup, or a channel is lost and not recovered, the receiver logs a Warning and tries again everyReconnectDelay; the client's automatic recovery repairs an ordinary connection loss on its own (RabbitMqReceiver.cs:17-19).[Rubric §10, Messaging & Integration]covers the delivery guarantee: a delivery is acknowledged only after its disposition copy is confirmed, and anything that fails is negatively acknowledged with requeue; a delivery whose settle failed is first held forBrokerTransportPolicies.SettleFailureBackoff(:13-15).Walkthrough
- Timings:
ReconnectDelay5 seconds (RabbitMqReceiver.cs:25),ChannelCheckInterval10 seconds (:28),DrainTimeout10 seconds (:31). An_inFlightcounter tracks deliveries being processed (:42). - The constructor (
:52-76) creates its own RabbitMqChannelOperations over the receiver's connection without owning it (:70) and fixes the fitted queue name (:75). ExecuteAsync(:102-128) loopsRunSessionAsync(:108), returns on cancellation (:110-113), logs any other failure (:114-117) and waitsReconnectDelaybefore the next session (:121).RunSessionAsync(:147-190) opens the connection, provisions the receive topology (:149-150), and when provisioning is off checks the queue passively (:151-154). It opens a consume channel with confirms off andconsumerDispatchConcurrencyset to the configured concurrency (:156-161), applies the prefetch window withBasicQosAsync(:164), and starts a consumer withautoAck: false(:166-168). It then polls everyChannelCheckInterval: a channel closed while the connection is open was closed by the broker, which recovery never repairs, so the session ends and a new one starts (:171-183). Thefinallydrains and closes the channel (:187-188).DrainAsync(:192-201) waits in 50 ms steps, up toDrainTimeout, for in-flight deliveries to settle.HandleAsync(:203-245) builds an IncomingBrokerMessage from the body, the decoded headers and the AMQPMessageId, falling back to the delivery tag (:208-211); runs the pipeline (:215); applies the disposition (:216-217); then acknowledges (:218). A cancellation during shutdown requeues at once (:220-224). Any other failure is a failed settle (:225-239): it is logged at Error with the backoff (:227), counted onBrokerMetrics.SettleFailureCountertaggedtransport=rabbitmqand the queue (:228-231), held forBrokerTransportPolicies.SettleFailureBackoff(30 seconds,BrokerTransportPolicies.cs:27) byBackOffAsync(:237), then requeued (:238). Without the hold, a settle that fails every time (a least-privilege user that may not publish to the retry or dead-letter exchange, say) would be redelivered at once in a hot loop; holding the delivery also holds its prefetch slot, which slows the consumer while the cause lasts (:233-236).BackOffAsync(:247-257) delays for the backoff and swallows the cancellation when the host is stopping, so a stopping host requeues at once.RequeueQuietlyAsync(:259-270) tolerates a closed channel, which returns unacknowledged deliveries to the queue by itself.StopAsyncandDispose(:79-90,:93-99) dispose the operations and the connection; the second disposal is a no-op.- Five
[LoggerMessage]methods (:272-285) cover consuming, session failure, channel loss, disposition failure (whose message carries the{Backoff},:281-282) and requeue failure.
- Timings:
Why it's built this way: separate connections for publishing and consuming, plus prefetch equal to twice the concurrency by default, keep acknowledgements flowing while the publisher is throttled; acknowledging after the confirmed copy makes a crash between the two produce a duplicate, never a loss, which the inbox absorbs.
Where it's used: registered as a hosted service by RabbitMqBrokerTransport only when the topology has subscriptions (
RabbitMqBrokerTransport.cs:59-73).Caveats / not-in-source: the drain waits at most 10 seconds and then closes the channel anyway; deliveries still in flight at that point (including one held in its 30-second settle-failure backoff) are returned to the queue by the broker and processed again.
RabbitMqBrokerTransport
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Transports.RabbitMq·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/RabbitMq/RabbitMqBrokerTransport.cs:25· Level 7 · class (internal sealed)
What it is: the built-in IBrokerTransport for
MessageBus:Provider=RabbitMq, the broker the Aspire development stack and the cross-service test tier run, written directly on RabbitMQ.Client against the same contract an adapter package implements (RabbitMqBrokerTransport.cs:8-11).Depends on: IBrokerTransport, BrokerTransportContext, MessageBusProviders, MessageBusSettings, IBrokerPublisher, IBrokerReceivePipeline, and the RabbitMQ types of this part: RabbitMqPublisher, RabbitMqChannelOperations, RabbitMqConnectionSource, RabbitMqProvisioner, RabbitMqReceiver, RabbitMqNames, RabbitMqConnectionSecurityNoticeService;
IHostEnvironmentandILoggerresolved for the notice.Concept: the transport strategy is taught at IBrokerTransport; this is its composition root for RabbitMQ. The topology it produces (fanout exchange per topic, one queue per host,
{queue}-error, TTL delay queues so delayed redelivery needs no plugin, persistent confirmed publishes, automatic recovery) is summarized in the class doc (RabbitMqBrokerTransport.cs:13-17) and taught at RabbitMqNames. See ADR-066 and ADR-118.Walkthrough
NamereturnsMessageBusProviders.RabbitMq(RabbitMqBrokerTransport.cs:28);MaxRedeliveryDelayisnull(:31), since a delay queue can hold any interval.Register(:34-74) parses the URI and reads the topology andProvisionTopology(:39-41). It then asks RabbitMqConnectionSecurityNoticeServiceDescribewhether the URI uses default credentials or cleartextamqp://, and only when it does registers that notice as a hosted service, resolvingIHostEnvironmentoptionally so the Development check runs at host start (:43-53); a host with anamqps://URI and its own credentials registers nothing there. Next it registers a singletonIBrokerPublisher: a RabbitMqPublisher over owning RabbitMqChannelOperations on a connection named{queue} (publish)(:55-57). A host with no subscriptions stops there (:59-62). Otherwise it resolves concurrency and prefetch (:64-65) and adds a RabbitMqReceiver hosted service on its own{queue} (receive)connection with its own provisioner (:66-73).ParseConnectionUri(:83-99) returnsnullfor a blank string, so the client defaultlocalhost:5672applies (:85-88), accepts an absoluteamqporamqpsURI (:90-94), and otherwise throws anInvalidOperationExceptionnamingMessageBus:ConnectionStringandConnectionStrings:rabbitmq(:96-98). The connection string resolution order is in the class doc (:20-22).ResolveConcurrency(:107-108): reads MessageBusSettingsConcurrentMessageLimitdirectly (MessageBus:ConcurrentMessageLimit), elseEnvironment.ProcessorCount, clamped to 1..65535.ResolvePrefetchCount(:117-118):MessageBusSettings.PrefetchCount(MessageBus:PrefetchCount), else twice the concurrency, so a finished delivery's slot is refilled without a broker round trip (:111-112).
Why it's built this way: a bad connection string fails at registration with an actionable message rather than as a runtime connection error, a weak but valid one is accepted with a startup Warning outside Development rather than refused, and separate publish and receive connections keep a throttled publisher from stalling consumer acknowledgements.
Where it's used: instantiated by
ResolveBrokerTransportwhen the provider isRabbitMq(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:216-219). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Transports/RabbitMq/RabbitMqBrokerTransportTests.csand, against a live broker,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.RabbitMq.Tests/RabbitMqBrokerTransportTests.cs.
JobClaim
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Scheduling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobRunner.cs:491· Level 0 · record (private nested, sealed)
What it is: the result of one attempt to claim a due job row: which row was due, the occurrence it was due at, the cron expression to compute the next occurrence from, and the claim token, which is null when a different replica won the row.
Depends on: nothing first-party. BCL only (
string,DateTime,Guid?). It exists solely as the return shape ofScheduledJobRunner.TryClaimNextDueAsync.Concept introduced, three answers in one return value. A claim attempt has three outcomes, not two: nothing was due, something was due and this replica took it, or something was due and another replica took it first.
[Rubric §15, Best Practices & Code Quality]assesses whether the code makes illegal states hard to express: the method returnsJobClaim?, sonullis "nothing due" and a non-null instance with a nullLockTokenis "lost the race" (ScheduledJobRunner.cs:442-445). Collapsing the latter two into onenullwould have cost the caller the ability to mark that name as attempted for this cycle and move on, which is exactly what stops the loop spinning on a row this replica will never own (ScheduledJobRunner.cs:399-406). A positional record gets that shape in one line with value equality and no mutable state.Walkthrough: four positional members, each documented (
ScheduledJobRunner.cs:486-491):JobName,DueOn(the occurrence the row was due at, used for the lag metric),CronExpression(what the next occurrence is computed from, read from the row rather than recomputed from settings so an in-flight schedule change cannot retarget a run in progress), andGuid? LockToken. It is constructed once, atScheduledJobRunner.cs:483, where the token is passed asclaimed == 0 ? null : lockToken: the count of rows the claimingExecuteUpdateAsyncactually matched IS the race result.Why it's built this way:
private sealed recordkeeps a purely internal carrier invisible to the package's public surface, so it costs nothing in API compatibility terms while still giving the claim path a named, immutable shape (ADR-074).Where it's used: returned by
TryClaimNextDueAsync(ScheduledJobRunner.cs:446-484) and consumed byRunDueJobsAsync(ScheduledJobRunner.cs:382-408).
ScheduledJobEntry
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Scheduling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobEntry.cs:20· Level 0 · class (sealed)
What it is: the persisted schedule and last-run record for one registered
IScheduledJob: one row per job name, upserted byScheduledJobRunneron every cycle. It carries both the schedule (expression, next occurrence) and the claim lease that makes a multi-replica host safe.Depends on: nothing first-party and nothing beyond
string,DateTimeandGuidfrom the BCL, which is why it is Level 0.Concept introduced, the framework bookkeeping entity.
[Rubric §4, DDD]assesses whether the domain model stays a model of the business: this class is deliberately not anIAuditableEntityand not an aggregate root, exactly likeOutboxMessage, because it is framework bookkeeping rather than domain state (ScheduledJobEntry.cs:8-14). The consequences are concrete: no soft-delete flag, so no global query filter applies to it; no audit stamps, so the save interceptors have nothing to write (which is why the runner can call a plainSaveChangesAsyncwith no user id,ScheduledJobRunner.cs:331-336); and no concurrency token, because its concurrency control is the explicit claim lease instead.[Rubric §8, Data Architecture]: the table is host-scoped and lives in theDefaultdata source only, unlike the outbox, which exists once per physical source (ScheduledJobEntry.cs:15-18). Jobs belong to a host, not to a database.[Rubric §11, Security]by omission: it also carries no user data, which is what keeps it in the audit trail's framework-entity exclusion set alongside the outbox and inbox rows (Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:113-119, this type at:118).Walkthrough, in the order the runner touches them:
JobName(ScheduledJobEntry.cs:26),requiredandinit-only: the primary key, matchingIScheduledJob.Name, so a job has exactly one schedule row per host.CronExpression(ScheduledJobEntry.cs:34),requiredwith a setter: the five-field UTC expression currently in force, which is either the job's code default or theScheduler:Jobs:{Name}:Cronoverride. The runner compares it against the resolved expression every cycle and recomputes the next occurrence only when it changed.NextRunOn(ScheduledJobEntry.cs:40): the UTC instant the job next becomes due. A row whose expression cannot be parsed is parked atDateTime.MaxValueso it is never claimed, which is how one bad cron string in configuration fails just that job.LastRunOn(:43),LastOutcome(:50, one ofSucceeded,Failed,Skipped),LastError(:57, truncated to the column width and cleared on success so the column always describes the LAST outcome rather than the last failure ever seen), andLastDurationMs(:60): the operator-facing run record.LockedUntil(:67) andLockToken(:74): the claim lease. Other replicas skip a row with an unexpired lease, so an occurrence runs once even with several replicas polling; the claiming replica stamps its outcome only on a row still carrying its own token, so a replica whose lease expired mid-execution cannot overwrite the record of the replica that took over.
Why it's built this way: ADR-074 chose to apply the outbox's proven claim-lease idiom to cron rather than adopt Hangfire or Quartz.NET, so the row shape is deliberately the minimum that idiom needs: a due time, a lease, and a token.
Where it's used: mapped by
ApplicationDbContext.ConfigureScheduler(Persistence/DbContexts/ApplicationDbContext.cs:594-619), which is gated: the entity is mapped only when the host setScheduler:Enabledand this context targets theDefaultsource (ApplicationDbContext.cs:586-599, the guard itself at:596-599), so a host that never opted in keeps exactly the model, and the migrations, it had before the scheduler shipped, and Cosmos DB never reaches the method at all (ApplicationDbContext.cs:591-592). The mapping setsToTable("ScheduledJobs", "dbo")(:603), theJobNamekey (:604), column widths matching the entity's documented truncation (:605-608), and one index onNextRunOnwith the two lease columns as included columns (:615-617), deliberately NOT filtered to unlocked rows, because the poll must also find rows whose lease has expired (that is how a dead replica's work is reclaimed,ApplicationDbContext.cs:610-614). Every read and write of the row lives inScheduledJobRunner.
ScheduledJobOverrideSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Scheduling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/SchedulerSettings.cs:69· Level 0 · class (sealed)
What it is: one entry under
Scheduler:Jobs:{Name}, the per-job override that lets a deployment retime a recurring job without touching code. Today it carries exactly one member, the cron expression.Depends on: nothing. It is the value type of SchedulerSettings
.Jobs(SchedulerSettings.cs:63) and is read by ScheduledJobRunner.Concept introduced, code default plus configuration override. An IScheduledJob ships with a
CronExpressioncompiled into it, which is the right default because the job's author knows what cadence the work needs. An operator who has to change that cadence for one environment should not need a release.[Rubric §17, DevOps]assesses whether operational behavior can be changed without a code change; this pair is the minimal answer: an absent entry leaves the compiled-in schedule in force, and a present, non-blankCronreplaces it (SchedulerSettings.cs:57-62,:71-77). The change needs a configuration edit and a host restart, not a release.[Rubric §15, Best Practices & Code Quality]: the override is keyed byIScheduledJob.Name, the job's own stable identity, so configuration and code agree on one name rather than on a class name that refactoring would break.Walkthrough: a single
string? Cron { get; init; }(SchedulerSettings.cs:78). The whole mechanism lives in the reader, not in this type:ScheduledJobRunner.ResolveCronExpressionlooks the job up by name and takes the override only when it is present AND non-blank, otherwise the job's own expression (ScheduledJobRunner.cs:179-183). Blank-means-absent matters, because a JSON key set to""is a common way to try to clear a value and would otherwise produce an unparseable schedule.Why it's built this way: the runner treats a changed expression as a schedule rewrite. On each cycle it reads the stored expressions (
ScheduledJobRunner.cs:284-288), leaves a row untouched when the resolved expression matches (recomputing every cycle would push the next occurrence forward forever and nothing would ever fire,:290-296), and otherwise recomputes the next occurrence from the current instant and either updates the row with a schedule-changed log (:304-309) or inserts a new one (:310-322). The settings themselves are read once: the runner snapshotsIOptions<SchedulerSettings>.Valueat construction (ScheduledJobRunner.cs:47), so an operator edit applies when the host restarts, and the first cycle after that restart performs the rewrite (SchedulerSettings.cs:73-76, ADR-074).Where it's used: ScheduledJobRunner only, through
SchedulerSettings.Jobs.Caveats: an override that does not parse is not rejected at startup, unlike the range-checked scalar settings in this namespace. The runner logs the parse failure (
ScheduledJobRunner.cs:304-308, message at:670-671) and records the job with the skipped outcome and aDateTime.MaxValuenext run (insert at:316-317, update at:359-368), so a bad cron string is an observable non-run rather than a failed boot. Editing the value on a running host changes nothing until the restart.
SchedulerMetrics
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Scheduling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/SchedulerMetrics.cs:16· Level 0 · class (internal, static)
What it is: the OpenTelemetry instrument set for the recurring job scheduler: one meter carrying a run counter, an execution-duration histogram, and a schedule-lag histogram, all emitted by
ScheduledJobRunner.Depends on:
System.Diagnostics.Metrics(BCL) only (SchedulerMetrics.cs:1). Nothing first-party.Concept introduced, the one-meter-per-feature instrument holder.
[Rubric §13, Observability & Operability]assesses whether a running system can be understood from outside: a background loop is invisible by construction (no request, no response code), so the only evidence that a schedule is healthy is telemetry. The three instruments here are chosen to answer the three operator questions: is it running, how long does it take, and is it on time.[Rubric §31, Cost/FinOps]shows up in the same design: the per-occurrence start and finish lines are logged atDebugrather thanInformationprecisely because a busy schedule would otherwise double the runner's steady-state log volume (ScheduledJobRunner.cs:778-785), and the numbers an operator alerts on come from these metrics instead. A host exports them by registering theMeterNamemeter; the Aspire service defaults (ConfigureOpenTelemetry) already do (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:335), and the doc records that the name is duplicated as a literal there because that package has no reference to Infrastructure (SchedulerMetrics.cs:5-14).Walkthrough:
MeterName = "MMCA.Common.Scheduler"(SchedulerMetrics.cs:19) and the single staticMeterbuilt from it (:21). The class doc is explicit that one meter serves every scheduler instrument and that a secondMeterwith this name must never be created (SchedulerMetrics.cs:11-14), since duplicate meters are a classic source of double-counted telemetry.BrokerMetricsrepeats the same shape for the broker transport.RunCounter(SchedulerMetrics.cs:28-31),scheduler.job.runs, unitruns, tagged byjobandoutcome: the failure rate of a schedule is this counter split by outcome.DurationHistogram(:39-42),scheduler.job.durationin seconds, tagged byjob, measured around the job's ownExecuteAsynconly so it excludes claim and bookkeeping cost. Its stated purpose is the lease relationship: a job whose duration approachesScheduler:LeaseSecondsis about to lose its claim mid-run (SchedulerMetrics.cs:33-38).LagHistogram(:50-53),scheduler.job.lagin seconds, the interval between an occurrence becoming due and actually starting. It is floored at zero, and a value near the polling interval is normal for an occurrence that landed just after a cycle (SchedulerMetrics.cs:44-49).
Why it's built this way:
internal static readonlyinstruments created once at type initialization means the runner records without resolving anything from DI, and keeping the meter name a constant on the same type is what lets a test assert against it.SchedulerMetricsTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/SchedulerMetricsTests.cs:13) pins the instrument surface.Where it's used:
ScheduledJobRunner.ExecuteClaimedJobAsyncrecords the lag before invoking the job (ScheduledJobRunner.cs:509-512) and the duration plus the outcome-tagged count after it returns (ScheduledJobRunner.cs:545-548).
SchedulerSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Scheduling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/SchedulerSettings.cs:16· Level 1 · class (sealed)
What it is: the
Schedulersection for the recurring-job runner: the on switch, the fallback poll interval, the row-claim lease, which engine holds theScheduledJobstable, and a per-job cron override map. Every property has a default, so a host that opts in needs onlyScheduler:Enabled(SchedulerSettings.cs:6-9).Depends on: DataSource, the engine enum, imported from
MMCA.Common.Application.Interfaces.Infrastructure(SchedulerSettings.cs:2,:52), and ScheduledJobOverrideSettings, the one-property class declared at the bottom of the same file (:69-79). Externals:System.ComponentModel.DataAnnotationsfor[Range](:1).Concept introduced: one setting that gates both the behavior and the schema. Most feature flags gate behavior.
Enabledalso decides whether theScheduledJobstable is mapped into the EF model at all: ApplicationDbContext readsIOptions<SchedulerSettings>withGetService(notGetRequiredService) so an absent registration reads as disabled rather than failing every context construction, then additionally requires the physical source to be the default one (ApplicationDbContext.cs:412-417). The consequence is the one worth learning: a host that leaves the flag false has exactly the model it had before the scheduler shipped, so its migrations never see the table (SchedulerSettings.cs:10-15).[Rubric §15, Best Practices & Code Quality]assesses whether adopting a framework feature is additive. Because registration and activation are separate (AddScheduledJobsbinds and registers the runner, but the runner returns immediately unlessEnabledis true,ScheduledJobRunner.cs:92-98), a host can ship the registration and turn the scheduler on per environment (MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:32-34).[Rubric §29, Resilience and Business Continuity]assesses safe behavior under replication.LeaseSecondsis what makes multiple replicas safe: a replica claims a job row for that many seconds and other replicas skip claimed rows, so no occurrence runs twice; if the claiming replica dies mid-execution, the row becomes claimable again once the lease expires (SchedulerSettings.cs:36-46, applied atScheduledJobRunner.cs:468). While a job runs, the holder renews its lease every half of this value (ScheduledJobRunner.cs:674,:585-589), so the lease no longer has to outlast the longest job; the trade-off is that a shorter lease frees a dead replica's row sooner at the cost of more writes and less time to retry a failed renewal before another replica can claim a job that is still running (SchedulerSettings.cs:39-43).[Rubric §31, Cost and FinOps]assesses idle-cost defaults.PollingIntervalSecondsis a BOUND on the smart wait, not a hot loop: the runner normally sleeps until the earliest due job and uses this value only to cap that sleep (SchedulerSettings.cs:28-34,ScheduledJobRunner.cs:130-133). The doc also names it as how quickly a configuration-driven schedule change is noticed, but the runner reads these settings once at construction (ScheduledJobRunner.cs:47), so in practice a changed setting takes effect after a host restart.Walkthrough: one static field, four
initproperties and one get-only dictionary.SectionName = "Scheduler"(SchedulerSettings.cs:19).Enabled(:26): defaultfalse, documented as the deliberate posture that adopting the framework must never add a table or a background loop to a host that did not ask for one.PollingIntervalSeconds(:34):[Range(1, 3600)](:33), default30.LeaseSeconds(:46):[Range(10, 3600)](:45), default300. The holder renews it every half lease while its job runs, so it does not need to exceed the longest job (:36-44).DataSource(:55): defaultDataSource.SQLServer. Jobs are host-scoped, so there is exactly oneScheduledJobstable per host rather than one per source, and this only names the relational engine that table lives on; Cosmos DB is not a valid value (:48-54). The runner resolves it againstDataSourceKey.DefaultName(ScheduledJobRunner.cs:232-233).Jobs(:63): a get-onlyDictionary<string, ScheduledJobOverrideSettings>keyed by IScheduledJob.Nameand bound fromScheduler:Jobs:{Name}.ResolveCronExpressiontakes the override only when the entry exists AND itsCronis non-blank, otherwise the job's compiled-in expression stands (ScheduledJobRunner.cs:179-183). A changed expression applies after a host restart (the runner snapshots the settings at construction,ScheduledJobRunner.cs:47): the first cycle compares the resolved expression against the stored one, leaves an unchanged row alone (recomputing it every cycle would push every schedule forward and nothing would ever fire), and otherwise rewrites the stored value and recomputes the next occurrence from the current instant (ScheduledJobRunner.cs:295-328).
Why it's built this way: a persistent, database-backed cron scheduler with per-row leases is the decision recorded in ADR-074; everything in this class is the operator-facing surface of it. Defaulting every property makes the section optional, which is the same fail-soft-on-absence, fail-fast-on-bad-value posture ADR-070 describes: the
[Range]guards run underValidateOnStart, so a bad value fails the boot rather than the first cycle.Where it's used: bound with validation in
AddScheduledJobs(MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:39-42), which registers the runner throughTryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, ScheduledJobRunner>())rather thanAddHostedService, precisely so two calls cannot start two runners racing for the same rows (MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:44-48). Read by ScheduledJobRunner (ScheduledJobRunner.cs:43,:47) and by ApplicationDbContext for the table gate (ApplicationDbContext.cs:415-417); the design-time helper supplies a default instance sodotnet efcan build a model without a host (DesignTimeDbContextHelper,DesignTimeDbContextHelper.cs:161-162).
GetUserPreferencesQuery
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.GetPreferences·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesQuery.cs:5· Level 1 · record (sealed)
What it is: the one-line query that asks for a single account's stored UI preferences. It is a positional record with exactly one member,
UserId, and it implementsIUserScopedRequest(GetUserPreferencesQuery.cs:5).Depends on:
IUserScopedRequest(IUserScopedRequest.cs:8), and theUserIdentifierTypealias, which resolves tointthrough the solution-wide global using (MMCA.Common/Source/Core/MMCA.Common.Domain/GlobalUsings.IdentifierType.cs:1; see primer §4 for the alias convention). No externals.Concept introduced: the one request record in this family that could be shared. Almost everything else in the shared Users use cases keeps its command record app-side, because ADC and Store disagree on the pipeline markers those records carry: both
DeleteUserCommandrecords, for instance, implementICacheInvalidatingwith aCachePrefixbuilt from their ownUsertype (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserCommand.cs:13,:17;MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/DeleteUser/DeleteUserCommand.cs:17,:20), which is a value no shared record could produce. This query carries no markers at all: it is notICacheInvalidating, notIQueryCacheable, notICommandWithRequest<out TRequest>. That absence is precisely what made it hoistable, and it is the rule worth taking away: a type moves into the framework when it has no app-specific policy attached to it.[Rubric §9: API & Contract Design]assesses whether the contract between layers is explicit and minimal. The query is the entire input contract for the read: one identifier, supplied by the controller from the authenticated principal rather than by the caller, so there is no way to ask for another account's preferences through this shape (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:146-151).[Rubric §6: CQRS & Event-Driven]assesses the separation of reads from writes. This is the read half of the culture/theme pair; its write counterpart is the app-sideChangePreferencesCommandhandled byChangePreferencesHandlerBase<TUser, TCommand>. Because it is a query, it flows through the shorter query pipeline (FeatureGate, Logging, Caching, handler) with no Validating and no Transactional decorator, per ADR-014.Walkthrough: one positional parameter.
UserId(GetUserPreferencesQuery.cs:5): the account to read. ImplementingIUserScopedRequestis satisfied by the record's generated property, so the shared handler base can read the target through the interface without knowing the record type (IUserScopedRequest.cs:11).
Why it's built this way: the query and its
UserPreferencesResponsereply were byte-identical in both app Identity modules, so the handler base could be made generic in theUseraggregate alone rather than also in the query type (GetUserPreferencesHandlerBase.cs:10-13). Preferences themselves are the persistence side of ADR-027 (culture) and ADR-028 (theme).Where it's used: constructed by
UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>in itsGET preferencesaction (UserAccountAuthControllerBase.cs:151) and handled byGetUserPreferencesHandlerBase<TUser>(GetUserPreferencesHandlerBase.cs:31-33). Both apps'AuthControllertake the closed handler interface as a constructor dependency (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:36,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/AuthController.cs:32), and both architecture suites use it as the query specimen when asserting decorator ordering (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:33,MMCA.Store/Tests/Architecture/MMCA.Store.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:30).
ScopedUserOverride
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Context·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ScopedUserOverride.cs:27· Level 5 · class (internal sealed)
- What it is: the scoped slot that lets a background scope act as a captured user.
Principalis null by default, which means "read through to HTTP"; a caller sets it before any handler is resolved, and clears it when a restored origin carries no user (ScopedUserOverride.cs:27-52). - Depends on:
System.Security.Claims.ClaimsPrincipal(BCL), andAmbientOriginfor the seed value itsPrincipalinitializer reads (ScopedUserOverride.cs:30). It is a two-member holder with no other collaborators. - Concept introduced, the override slot behind a decorator.
[Rubric §11, Security]assesses whether identity flows correctly across an async or process boundary rather than defaulting to anonymous or leaking across scopes. HTTP requests already have an ambient identity from the authentication middleware, but background work (the internal command processor, the outbox processor, a broker consumer) runs on a scope with no HTTP context at all. This class is the extension point DI resolves per scope: when nothing has calledSet,Principalstays null andImpersonatingCurrentUserServicereads through to whatever the innerICurrentUserServicewould have returned anyway. - Walkthrough
Principal(ScopedUserOverride.cs:30) has a private setter, soSetandClearare the only ways to change it after construction. Its initializer isAmbientOrigin.Current?.BuildPrincipal(): the scope reads the enclosing hop's published origin once, at construction, and owns its copy from then on (ScopedUserOverride.cs:20-26,:30). A scope a handler opens for itself from the root factory inside a delivery therefore starts as the original interaction, while an HTTP request (which never publishes an origin) starts null. Nothing is shared or mutated across scopes, which is the leak a live ambient override would have caused.Set(principal)(ScopedUserOverride.cs:36-40) null-guards the argument and assigns it.Clear()(ScopedUserOverride.cs:51) setsPrincipalback to null. It is reached throughAmbientOriginwhen a restored origin carries no user (a row or message raised by the system), and its doc comment names why it is necessary rather than optional (:42-50): the outbox processor opens a fresh scope per row, but this override is seeded at construction from whatever origin is flowing at that moment, so without an explicit clear a system-raised row could still act as the principal that flow carried (:44-49).
- Why it's built this way: ADR-114 needs internal command handlers to see the identity that originally scheduled the work, through the same
ICurrentUserServiceinterface every other handler already depends on, rather than a parallel API only background code would use. - Where it's used: written by
AmbientOrigin.Restore(set or cleared on every restore) and read byImpersonatingCurrentUserService. Registered per scope inDependencyInjection.cs(2 references). Exercised directly byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Consumers/IntegrationEventConsumerContextTests.cs(4),MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Outbox/Processing/OutboxProcessorContextRestoreTests.cs(4), andMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/InternalCommandTestHarness.cs(2). - Caveats / not-in-source: like
TenantContext, it is not thread-safe, but as a scoped service on a single logical unit of work (one HTTP request, one dequeued message, one internal command) that is not a property it needs.
AmbientOrigin
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Context·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:21· Level 1 · class (internal static)
- What it is: the shared helper that flattens a capturing principal's roles and permission claims for storage, rebuilds a
ClaimsPrincipalfrom what was stored, restores a captured user, tenant, and correlation id onto a fresh scope, and publishes that restored origin on the async flow so scopes opened inside the hop inherit it (AmbientOrigin.cs:21-368). It is the one place this logic exists; everything that later replays a captured origin, an internal command row, an outbox row, a broker message, calls into it. - Depends on:
ScopedUserOverrideandITenantContext(fromTenantContext) as the scope services it restores onto;OriginSnapshotas the published value andRestoreHandleas the disposable it returns;ICorrelationContextfor the correlation id; theUserIdentifierTypealias;System.Security.ClaimsforClaim/ClaimsIdentity/ClaimsPrincipal;System.Text.Jsonfor the permissions array;AuthClaimTypesfor the subject and permission claim types. - Concept introduced, one flatten/rebuild pair reused across every async boundary.
[Rubric §11, Security]assesses whether identity propagation is centralized rather than reimplemented per call site, and[Rubric §8, Data Architecture]assesses whether the tenancy invariant holds even off the request path.MaxRolesLength(AmbientOrigin.cs:36-40, value 512) is the column width shared byInternalCommands.UserRolesandOutboxMessages.UserRoles;FlattenRolesfits the column rather than throw, by keeping only the whole leading roles that fit and dropping the trailing ones (:74-94): cutting a name mid-word would restore a role nobody holds and lose the real one. It is also explicitly null-tolerant even thoughICurrentUserService.Rolesis declared non-nullable, becauseRolesis a default interface member that runs against hand-written doubles and mocks that stub only the properties a caller touches (:47-53). A null there must read as "no roles", never as a capture that throws inside a save. - Concept, permissions travel at full fidelity as JSON. Roles alone no longer describe what a principal may do, so
FlattenPermissions(AmbientOrigin.cs:110-126) captures the principal's distinctAuthClaimTypes.Permissionclaims, in claim order, as a JSON array of strings, and returns null when there are none. Unlike the roles list nothing is ever dropped or cut, because theUserPermissionscolumns are unbounded and a missing permission would deny a deferred command the inline request was allowed to run (:102-107); JSON rather than a delimited list because nothing constrains what a permission name may contain.ParsePermissions(:135-152) reads it back and treats a malformed value as a writer bug that yields no permissions rather than failing the hop, so deferred work is authorized by its roles alone, never by more than was captured. - Concept, the tenant is the one value
Restorewill not overwrite.Restore(AmbientOrigin.cs:255-300) documents an explicit asymmetry (:213-225): the principal and correlation id are set or cleared on every call, because a scope reused across several messages cannot let one message's user answer for the next, butITenantContextis single-valued for the life of a scope by contract, since a scope whose tenant changed mid-flight has already read rows under the previous one.RestoreTenant(:302-327) therefore sets the captured tenant on a scope that has not resolved one, leaves a scope that already resolved the same tenant (a database-per-tenant target) as it is, and throwsInvalidOperationExceptionwhen the scope already resolved a different tenant (:318-324), because running the captured user's work under another tenant's query filter is never right. The throw comes before any principal is installed, andRestorecatches it only to put the enclosing origin back before rethrowing (:273-281), so the flow is left as it was found; the hop then fails the row or message, which is retried and finally dead-lettered where an operator sees it (:306-307). - Concept, the restored origin is also published on the async flow. Integration event handlers are singletons that open their own scope from the root factory, a scope that never sees the
Restorecall.Restoretherefore also writes anOriginSnapshotinto a privateAsyncLocal(AmbientOrigin.cs:26,:291-297), exposed read-only asCurrent(:34).TenantContext,ScopedUserOverrideandCorrelationContextreadCurrentonce, at construction, and seed themselves from it (TenantContext.cs:20,ScopedUserOverride.cs:30,CorrelationContext.cs:13), so a handler's own scope runs as the original interaction (:231-242, the "Scopes opened inside the hop inherit it" remark). The snapshot carries the tenant and correlation id the restored scope ended up with, not the raw captured ones, so a database-per-tenant scope whose tenant was already fixed hands that tenant down (:295-296). - Walkthrough
FlattenRoles(roles)(AmbientOrigin.cs:60-95) joins the roles with a comma, keeps only the whole leading roles that fitMaxRolesLength, and returns null for a null or empty source (or when not even the first role fits).FlattenPermissions(principal)(AmbientOrigin.cs:110-126) serializes the distinct permission claims to a JSON array;ParsePermissions(userPermissions)(:135-152) is its tolerant inverse.BuildPrincipal(userId, userRoles, userPermissions, authenticationType)(AmbientOrigin.cs:179-206) returns null whenuserIdis null, meaning no user was captured, and the execution stays anonymous rather than inventing an identity. Otherwise it builds asubclaim from the id, one role claim per comma-separated entry and oneAuthClaimTypes.Permissionclaim per stored permission (:202-203), then wraps them in aClaimsIdentitystamped withauthenticationType, which is what makesIsAuthenticatedtrue. Themfaclaim is deliberately not propagated: a step-up proves a live interaction, deferred work runs later without that person present, so work that needs a second factor cannot run deferred and must run inline in the request that carried the step-up (:162-168).Restore(services, userId, userRoles, userPermissions, tenantId, correlationId, authenticationType)(AmbientOrigin.cs:255-300) returns anIDisposable. It first saves the enclosing origin and withdraws it (:266-267), so a carrier constructed during this restore belongs to this hop and does not seed itself from the previous one. It resolves each of the three scope services withGetServicerather than a required resolve, so a bare provider (a directly constructed test fixture) simply restores nothing rather than failing the hop (:226-230). It sets the tenant first viaRestoreTenant(:273-281,:310-327), because it routes the scoped context factory to the right database and every repository resolved afterward reads its query filter from it; a tenant mismatch throws here, after the enclosing origin is put back and before anything else is touched. Then it sets or clearsScopedUserOverrideviaRestorePrincipal(:283,:330-345); then sets the correlation id when one was carried (:285-289); then publishes the newOriginSnapshot, now including the permissions, and returns aRestoreHandlethat puts the previous origin back (:291-299). Callers dispose the handle when the message or row is done, so the next one cannot inherit it.Suppress()(AmbientOrigin.cs:355-360) withdraws the published origin until the returned handle is disposed. It exists for the case where an explicit choice must win over an enclosing hop: its doc comment namesTenantDataSourceTargets.CreateTenantScope(:349-353).
- Why it's built this way: centralizing flatten, rebuild, and restore in one internal static class means every caller, the internal command scheduler, the outbox processor, the broker consumers, restores context identically; a divergence in any one of them would have been a silent identity or tenant leak rather than a compile error.
- Where it's used: called by
ConsumerOriginRestore(2 references) and directly byInternalCommandScheduler(2),InternalCommandProcessor(3),InternalCommandOriginCapture(3),TenantDataSourceTargets(2, theSuppresscaller),BrokerMessageBus(2),DbContextFactory(2), andOutboxProcessor, all underMMCA.Common/Source/Core/MMCA.Common.Infrastructure. The seeding readers areScopedUserOverride,TenantContextandCorrelationContext. Exercised byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Context/TenantScopeInsideARestoredHopTests.cs(7 references), which pins both tenant outcomes: a restore onto a scope resolved to another tenant throws without installing the principal (TenantScopeInsideARestoredHopTests.cs:68-76) and one onto the same tenant succeeds (:84); and byAmbientOriginFlattenRolesTests.cs(6), which covers the roles fit and the permissions round trip (AmbientOriginFlattenRolesTests.cs:17,:39). - Caveats / not-in-source: not determinable from this source whether a host could reasonably bypass
Restoreand set the three scope services directly; every first-party caller goes through this helper. TheAsyncLocalis the one ambient value in this design, so a caller that drops the returned handle leaves the origin published for the rest of that async flow.
OriginSnapshot
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Context·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:377· Level 5 · record (internal sealed)
- What it is: the immutable value
AmbientOriginpublishes on the async flow while a background hop is running: the user id, roles, permissions, tenant, correlation id and authentication type the hop restored (AmbientOrigin.cs:377-388). - Depends on: the
UserIdentifierTypealias andSystem.Security.Claims.ClaimsPrincipal; its one method calls back intoAmbientOrigin.BuildPrincipal(:363). - Concept introduced, a snapshot instead of a shared carrier.
[Rubric §11, Security]assesses whether identity propagation avoids leaking across scopes. Publishing an immutable record rather than the liveScopedUserOverrideorTenantContextmeans a scope that seeds from it copies values and then owns them; no mutable state is shared between the hop's scope and a scope a handler opens later. - Walkthrough
- Positional members (
AmbientOrigin.cs:377-383):UserId(nullable, null for system-raised work),UserRoles(the comma-separated list),UserPermissions(the permission claims as a JSON array, or null),TenantId,CorrelationId(both the values the restored scope ended up with) and a non-nullAuthenticationType. BuildPrincipal()(AmbientOrigin.cs:387) rebuilds the principal from the stored id, roles and permissions, or returns null when no user was captured.ScopedUserOverridecalls it from its initializer (ScopedUserOverride.cs:30).
- Positional members (
- Why it's built this way: the roles and permissions stay in their flattened string forms so the snapshot carries exactly what the stored row or message header carried, and rebuilding stays in the one helper that already owns that logic.
- Where it's used: only inside
AmbientOrigin(Current,Restore) and by the three seeding carriers throughCurrent; no other file names the type. - Caveats / not-in-source: none beyond the above.
RestoreHandle
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Context·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/AmbientOrigin.cs:364· Level 5 · class (private sealed, nested inAmbientOrigin)
- What it is: the
IDisposablethatRestoreandSuppresshand back; disposing it puts the previously published origin back (AmbientOrigin.cs:364-367). - Depends on:
OriginSnapshot(the saved previous value) and the privateCurrentOriginAsyncLocalof its enclosingAmbientOrigin(:24). - Concept introduced, scoped publication through a disposable.
[Rubric §1, SOLID]assesses whether a lifetime is expressed by the type system rather than by a convention. The handle makes "publish for the duration of this message or row" ausing-shaped contract:Disposeis the single lineCurrentOrigin.Value = previous(:242), so nesting restores correctly and the next message in a reused scope cannot inherit the last one's origin. - Walkthrough: a primary constructor capturing
previous(AmbientOrigin.cs:364), andDispose(:242) assigning it back.Restorepasses the origin it displaced (:187) andSuppresspasses the one it withdrew (:236). - Why it's built this way: a private nested class keeps the
AsyncLocalwritable only fromAmbientOrigin, while callers see onlyIDisposable. - Where it's used: constructed in
RestoreandSuppressin the same file; callers hold it asIDisposable. - Caveats / not-in-source: not determinable from source whether every caller disposes it on all paths; that is each caller's responsibility.
TenantContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Context·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/TenantContext.cs:14· Level 6 · class (public sealed)
- What it is: the scoped holder of "which tenant is this scope running as". It starts unresolved (unless it is created inside a background hop, below), is set exactly once per scope, and refuses to be changed to a different value afterwards (
TenantContext.cs:6-14). An unresolved scope reads no tenant-owned rows; a system operation that must see every tenant declares so withSetAllTenants, and that declaration is just as final (TenantContext.cs:8-9,:29-44). A scope created while an outbox row, broker message or internal command is being delivered starts with the tenant that hop restored, so a handler that opens its own scope runs under the original tenant (TenantContext.cs:20). - Depends on:
ITenantContextas the contract,System.Globalizationfor the exception message, andAmbientOriginfor the seed read in the constructor (TenantContext.cs:20). Otherwise it is a three-property object with two guarded setters. - Concept introduced, the ambient scope value with a write-once discipline.
[Rubric §11, Security]assesses whether an isolation boundary can be crossed by accident, and[Rubric §8, Data Architecture]assesses whether the tenancy model is enforced by the infrastructure rather than by convention. Multi-tenancy here (ADR-073) is a shared-schema query filter plus database-per-tenant routing, which means the tenant value silently participates in every read (the namedTenantquery filter), every write (the save interceptor), every tenant-scoped cache key, and the choice of physical database. Reassigning it mid-scope would therefore be catastrophic in a very quiet way: rows already tracked by the context were fetched under the old tenant, and the next save would attribute them to the new one. The exception message spells out exactly that (TenantContext.cs:73-79), and it ends with the remedy rather than just the complaint: start a new scope. - Walkthrough
- The public parameterless constructor (
TenantContext.cs:20) assignsTenantId = AmbientOrigin.Current?.TenantId, so the value is read once at construction and null outside a hop (every HTTP request). TenantIdhas a private setter (TenantContext.cs:23), so the only way to write it after construction is throughSetTenant.IsResolvedisTenantId is not null(TenantContext.cs:26). Unresolved fails closed: the interface contract says an unresolved tenant reads no tenant-owned rows at all, so "see everything" is always a decision in code and never the accident of a request that carried no tenant (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ITenantContext.cs:12-16).IsAllTenants(TenantContext.cs:29, private setter) is that decision.SetAllTenants()(TenantContext.cs:32-44) throwsInvalidOperationExceptionwhen a single tenant is already set, because a scope cannot be widened after it has read one tenant's rows (:34-41), and otherwise sets the flag (:43); calling it again is a no-op.DbContextFactorywires the flag into the context (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:153), where the namedTenantfilter readsIsAllTenantsScope || TenantId == CurrentTenantId(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:748).SetTenant(tenantId)(TenantContext.cs:47-80) has four branches. It null- and whitespace-guards the argument (:49); throws when the scope was declared all-tenants, since anything already read saw every tenant (:51-58); assigns and returns when nothing is set yet (:60-64); returns silently when the same value is re-asserted (:68-71); and throwsInvalidOperationExceptionon a genuine change (:73-79).- The idempotent same-value branch is the load-bearing one, and the comment at
:66-67names the scenario: the resolution middleware and a background worker that re-asserts the tenant on the same scope must not fight each other. Same value is a no-op, different value is a hard failure.
- The public parameterless constructor (
- Why it's built this way: the registration comment in
AddServices(whichAddInfrastructurecalls,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:315) explains why the class is always registered rather than opted into (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:379-383): an always-on registration costs one object per scope and removes a whole class of "works until someone forgets the opt-in" bug. That comment still describes an unresolved tenant as "no tenancy", which no longer matches the fail-closed contract onITenantContext(ITenantContext.cs:12-16); trust the interface and the class doc (TenantContext.cs:8-9). OnlyAddMultiTenancy(configuration)turns resolution at the API edge on. - Where it's used: written by
TenantResolutionMiddlewareon the request path (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs:71), and by the per-tenant background paths that create their own scope: database initialization (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:214),OutboxProcessor,OutboxCleanupService,OutboxAdministration, andAuditTrailCleanupJob. It is read byDbContextFactoryfor routing, byTenantSaveChangesInterceptor, and by the caching decorators throughTenantCacheKey. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Context/TenantContextTests.cs, and exercised for routing byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Tenancy/DbContextFactoryTenantTests.cs. - Caveats / not-in-source: the class is not thread-safe, and does not need to be as a scoped service on a request path, but two threads sharing one scope and racing on
SetTenantwith different values is not guarded against.
GetUserPreferencesHandlerBase<TUser>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.GetPreferences·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandlerBase.cs:19· Level 8 · class (abstract)
What it is: the shared preference-read workflow, and the only query handler among the Users bases. Load the account through the read repository and project its two preference fields into a
UserPreferencesResponse(GetUserPreferencesHandlerBase.cs:19,:31-43).Depends on:
IUnitOfWorkas its single primary-constructor parameter (:19); implementsIQueryHandler<in TQuery, TResult>closed overGetUserPreferencesQueryandResult<UserPreferencesResponse>(:20). One constraint:TUseris anAuditableBaseEntity<TIdentifierType>implementingIUserPreferences(:21). Also usesError. No logger, and no externals beyond the BCL.Concept introduced: one generic parameter is enough when nothing app-specific rides on the request. This is the contrast case for the command bases above. Because
GetUserPreferencesQuerycarries no pipeline markers, it could be shared outright, so the base is generic in theUseraggregate only (:10-13). Note also the weaker entity constraint:AuditableBaseEntity<UserIdentifierType>rather thanAuditableAggregateRootEntity<...>(:21), because a read needs no domain events and no aggregate behavior. Constraining to the least the workflow actually uses is the pattern worth copying.[Rubric §6: CQRS & Event-Driven]assesses read/write separation. The handler takes the read repository viaGetReadRepository(:37) rather thanGetRepository, and never callsSaveChangesAsync. The class remarks state that the read repository is the correct choice for a query handler, which never saves (:14-17).[Rubric §12: Performance & Scalability]assesses avoidable work. The read repository is the no-tracking path, so this query does not materialize an EF change-tracker entry for a preference lookup; the class remarks state it plainly: the read is no-tracking (:15-16). Note the related trap the workspace has hit elsewhere: a no-tracking source poisons a whole composed query, which is precisely why mutation handlers such asChangePreferencesHandlerBase<TUser, TCommand>keep usingGetRepositoryinstead.[Rubric §15: Best Practices & Code Quality]assesses consistency of error shape. The not-found path produces the identicalError.NotFound.WithSource(HandlerName).WithTarget(typeof(TUser).Name)construction the command bases use (:40-41), so every account use case reports a missing user the same way.Walkthrough: one protected member and one method.
- Primary constructor (
:19):unitOfWorkonly. HandlerName(:28): the sameGetType().Namedefault, so an app subclass namedGetUserPreferencesHandlerreports that name as the errorsource(:23-27).HandleAsync(GetUserPreferencesQuery, CancellationToken)(:31-43): null-guards the query (:35); resolvesGetReadRepository<TUser, UserIdentifierType>()(:37); loads byquery.UserId(:38); and returns either the stampedError.NotFoundfailure (:40-41) or a success wrappingnew UserPreferencesResponse(user.PreferredCulture, user.PreferredTheme)(:42). A ternary, not a branch chain: the whole method is a load and a projection.
- Primary constructor (
Why it's built this way: the query and the response are shared types, so the only decision the base has to make is which repository is correct for a read, and it uses the no-tracking one (
:10-17). Preferences are read at login to reapply a returning user's culture and theme across devices (ADR-027, ADR-028), which is why the read path is worth keeping cheap.Where it's used: subclassed as an empty, name-preserving class in both apps (
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandler.cs:13-14,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandler.cs:12-13). Consumed through the closedIQueryHandler<GetUserPreferencesQuery, Result<UserPreferencesResponse>>interface byUserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>(UserAccountAuthControllerBase.cs:46,:58,:150-151). Pinned byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/GetUserPreferencesHandlerBaseTests.cs:14through a test subclass (:87), and by each app's own handler tests.Caveats: the soft-delete global query filter applies to this read like any other, so a soft-deleted account resolves to
nulland returnsNotFoundrather than its stored preferences. That behavior comes from the persistence layer, not from anything in this class.
ScheduledJobModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Scheduling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobModelContributor.cs:19· Level 9 · class (internal, sealed)
What it is: the model contributor that maps the
ScheduledJobEntrytable (the recurring job store) into the EF model, registered byAddScheduledJobs(ADR-148). It maps the table only when two conditions both hold:Scheduler:Enabledis true and the physical source is theDefaultone (ScheduledJobModelContributor.cs:10-17).Depends on:
IOptions<SchedulerSettings>as its single primary-constructor parameter, implementingIModelContributor(:19). Also usesModelContributorPhase,PhysicalDataSource,DataSourceKey,DataSourceandDataSourceEngines. Externals:Microsoft.EntityFrameworkCoreandMicrosoft.Extensions.Options(:1-2).Concept introduced: an optional framework table is contributed, not hard-coded.
[Rubric §8, Data Architecture]assesses whether schema follows ownership. The scheduler table is host-scoped, soAppliesToadmits only the source namedDataSourceKey.DefaultName(:25-27): the table lives in exactly one database, unlike the outbox, which exists once per physical source (:14-16).[Rubric §15, Best Practices & Code Quality]assesses whether adopting a framework feature is additive. The sameAppliesToalso readssettings.Value.Enabled(:26), so a host that never opted in keeps a model byte-identical to what it was before the scheduler shipped, and its migrations never see the table (:12-14).Walkthrough:
Phase(:22):ModelContributorPhase.AfterEntityPasses.AppliesTo(PhysicalDataSource)(:25-27):EnabledAND an ordinal match of the source name againstDataSourceKey.DefaultName.Configure(ModelBuilder, DataSource)(:30-51):ToTable("ScheduledJobs", "dbo")(:33);JobNameas the key (:34);JobNameandCronExpressionat 128 non-Unicode characters,CronExpressionrequired,LastOutcomeat 32 non-Unicode,LastErrorat 2048 (:35-38); and one index onNextRunOnnamedIX_ScheduledJobs_NextRunOnthat carriesLockedUntilandLockTokenas included columns through the engine's ownIncludeColumns(DataSourceEngines.For(engine),:46-50).
Why it's built this way: the index is deliberately NOT filtered to unlocked rows. The claim poll in
ScheduledJobRunnermust also find rows whose lease has expired (that is how a dead replica's work is reclaimed), and aLockedUntil IS NULLfilter would hide exactly those; including the lease columns instead answers the predicate from the index without a key lookup per candidate row (:40-45). Moving optional framework tables into contributors is the decision in ADR-148; the scheduler itself is ADR-074.Where it's used: registered by
AddScheduledJobswithTryAddEnumerable(ServiceDescriptor.Singleton<IModelContributor, ScheduledJobModelContributor>())(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:52, comment:50-51), beside its siblingAuditTrailModelContributor(:125).DesignTimeDbContextHelperadds it when the design-time options enable the scheduler (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:192). Pinned bySchedulerModelGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/SchedulerModelGateTests.cs:27) andDependencyInjectionModelContributorTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/DependencyInjectionModelContributorTests.cs:23).
ImpersonatingCurrentUserService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Context·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ImpersonatingCurrentUserService.cs:20· Level 9 · class (internal sealed)
- What it is: the
ICurrentUserServicedecorator that lets background work answer identity questions as the user who originally triggered it. Every member checksScopedUserOverride.Principalfirst and falls through to the innerICurrentUserServiceonly when nothing was captured (ImpersonatingCurrentUserService.cs:20-52). - Depends on:
ICurrentUserService innerandScopedUserOverrideas its two primary-constructor parameters (ImpersonatingCurrentUserService.cs:20-22), and implementsICurrentUserServiceitself, so it is a drop-in replacement wherever the interface is consumed. - Concept introduced, a decorator that changes the answer, not the pipeline stage.
[Rubric §11, Security]assesses whether a component's identity claims are consistent with where the code is actually running. Unlike the CQRS pipeline decorators, which wrap a handler call, this decorator wraps the identity service itself: any code that resolvesICurrentUserService, whether a handler, a query-cache key builder, or an audit-field stamper, gets the captured identity automatically onceAmbientOrigin.Restorehas set the override, with no code path needing to know it is running outside an HTTP request. - Walkthrough
User(ImpersonatingCurrentUserService.cs:24-25) returnsuserOverride.Principal ?? inner.User.UserId(ImpersonatingCurrentUserService.cs:27-29) readsGetUserId()off the override principal when set, else delegates toinner.UserId.Role(ImpersonatingCurrentUserService.cs:31-35) reads the firstClaimTypes.Roleclaim off the override principal when set, else delegates toinner.Role.GetClaimValue<T>(claimType)(ImpersonatingCurrentUserService.cs:38-52) delegates outright toinner.GetClaimValue<T>when there is no override principal (:41-44); otherwise it reads the claim and parses it itself. The comment at:46-48records a real trap: claims are machine-written in the invariant culture exactly as the innerCurrentUserServicereads them, so parsing under the ambient culture would misread decimal andDateTimeseparators.
- Why it's built this way: ADR-114 needs internal command handlers, and anything else running on a restored scope, to see the originally scheduling user through the exact same
ICurrentUserServicecontract handlers already depend on. A decorator over the interface, rather than a branch inside every consumer ofICurrentUserService, keeps that substitution invisible to callers. - Where it's used: registered in
DependencyInjection.cs(1 reference) as the decorator over the host's realICurrentUserService. Depends onScopedUserOverride(1 reference, the file that declares it also references this type in return). Exercised byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/InternalCommandTestHarness.cs. - Caveats / not-in-source: not determinable from this source whether every host registers this decorator or only those that process internal commands or outbox messages; the registration site itself is the authority on when it is wired in.
ScheduledJobRunner
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Scheduling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobRunner.cs:40· Level 10 · class (sealed, partial, BackgroundService)
What it is: the framework's recurring job scheduler. A
BackgroundServicethat runs the host's registeredIScheduledJobimplementations on their cron schedules, using a persistent job store (ScheduledJobEntry) and the outbox processor's claim-lease idiom so an occurrence executes exactly once across every replica.Depends on:
IServiceScopeFactory,ILogger<ScheduledJobRunner>,IOptions<SchedulerSettings>(SchedulerSettings),IDataSourceResolver, and an optionalTimeProvider(ScheduledJobRunner.cs:40-45). At run time it resolvesIDbContextFactoryper cycle (:231) and works againstApplicationDbContext; it emits throughSchedulerMetricsand returns its claim results asJobClaim. Externals: EF Core (ExecuteUpdateAsync),Microsoft.Extensions.Hosting, and Cronos, aliased asCronSchedule(ScheduledJobRunner.cs:13).Concept introduced, the claim-lease scheduler.
[Rubric §29, Resilience & Business Continuity]assesses whether work survives failure: a schedule that lives in a timer dies with the process, so the schedule lives in a table and the loop only reads it.[Rubric §12, Performance & Scalability]assesses scale-out: an interval-driven hosted service runs on every replica, so scaling a service to three instances silently triples a purge. The fix is the outbox's claim: a singleExecuteUpdateAsyncthat stampsLockedUntilandLockTokenover aWhereadmitting only unleased-or-expired rows, where the count of matched rows IS the race result (ScheduledJobRunner.cs:471-483). Two replicas both issue that update and exactly one matches.[Rubric §13, Observability & Operability]: every branch that a human would need to explain later has a[LoggerMessage]line, including the ones that do nothing (disabled scheduler, duplicate job name, lease lost, a stamp that needed its retry).[Rubric §14, Testability]: the injectedTimeProviderplus aninternalRunCycleAsyncmean a test drives one whole cycle deterministically without waiting on wall-clock timers (ScheduledJobRunner.cs:221-222).Walkthrough:
- State and constants.
_settingssnapshotsIOptions<SchedulerSettings>.Valueonce (ScheduledJobRunner.cs:47), and_timeProviderfalls back toTimeProvider.System(:48). The three outcome stringsSucceeded,FailedandSkippedare named constants (:51,:54,:60),MaxErrorLengthis 2048 and matches theLastErrorcolumn width (:63),StartupDelayis 15 seconds so the host finishes module registration and migration before the first cycle touches the table (:70), andMinimumWaitis one second, the floor that stops an overdue row hot-looping the runner (:73).StampTimeoutis five seconds (:81), the budget for each attempt at recording an outcome after a job has returned, andStampRetryDelayis two seconds (:87), the wait before the one retry of a failed stamp: long enough for a connection blip or a failover to clear, short against the lease the row still holds (:83-86). SeeExecuteClaimedJobAsyncbelow for both. ExecuteAsync(:90-144), the loop. It returns immediately whenScheduler:Enabledis false, after one log line (:92-98), so a disabled scheduler is visible in the logs of a host that expected it without costing a line per cycle. Then the startup delay (:100-107), then forever: run a cycle, and swallow exceptions in two distinct ways.OperationCanceledExceptionduring shutdown breaks the loop (:116-120); any other exception is logged and the loop waits out the interval (:121-128), because one bad cycle (an unreachable database, a model mismatch) must not take the scheduler down for the life of the process.- The smart wait.
ComputeWaitTime(:155-169) is a pure static function: the polling interval when nothing is registered, otherwise the time until the earliest upcoming occurrence, floored atMinimumWaitand capped at the configured interval. This is the same "sleep until there is something to do" shapeOutboxProcessoruses, and it is what keeps an idle scheduler from polling on a fixed tick. RunCycleAsync(:222-245). One DI scope per cycle. It resolves the registered jobs (:225), returns early when there are none (:226-229), takes the context for theDefaultlogical source on the configured engine throughIDataSourceResolver(:231-233), reconciles registrations, runs due jobs, and finally reads back the earliestNextRunOnacross the registered names (:238-244) which becomes the next wait.ResolveRegisteredJobs(:252-267) groupsGetServices<IScheduledJob>()byName(ordinal) and keeps the first of each group, logging a collision rather than throwing (:260-263). Two jobs sharing a name would share one schedule row, and the design choice is that one mis-registered module must not stop every other job.SyncRegistrationsAsync(:276-337) reconciles the table against the registered jobs. It reads the stored expressions once (:284-288), and for each job compares the resolved expression against the stored one: unchanged means leave the row alone (:296-302), with the comment naming the bug that would otherwise appear, recomputingNextRunOnevery cycle would push every schedule forward forever and nothing would ever fire. A changed expression goes through the set-basedUpdateScheduleAsync(:343-375) so a row another replica is currently executing is not disturbed by the change tracker; a new job is inserted (:316-328). An unparsable expression parks the row atDateTime.MaxValueand recordsSkippedinstead of throwing (:304-308,:318-325, and on the update path at:365-374).ResolveCronExpression(:179-183) is the configuration override point:Scheduler:Jobs:{Name}:Cronwhen present and non-blank, otherwise the job's compiled-in default.TryGetNextOccurrence(:193-214) wraps Cronos and catches exactlyCronFormatExceptionandArgumentException(:206), converting a malformed expression into a parked row plus an error message rather than a crashed runner.RunDueJobsAsync(:382-408) claims and runs one row at a time, tracking anattemptedset so each name is tried at most once per cycle (:387-399). AJobClaimwith a nullLockTokenmeans another replica won that row, so it is skipped rather than retried (:401-406). A won claim runs throughExecuteClaimedJobGuardedAsync(:415-437), so a failure around one job (the job's own exception is already caught inside) costs only that job: a shutdown cancellation is rethrown (:427-430), anything else is logged atErrorthroughLogJobCycleStepFailedand the cycle moves on to the next due job (:431-436). That job's row keeps its lease and is re-claimed once the lease runs out, the at-least-once behavior ADR-074 records (:410-414).TryClaimNextDueAsync(:446-484) reads the earliest due, unleased row (:453-460), mints aGuidtoken and a lease ofScheduler:LeaseSecondsfrom now (:467-468), then issues the conditional claim update described above (:473-481).ExecuteClaimedJobAsync(:499-594) records the lag (floored at zero so a clock adjustment cannot publish a negative duration,:509-512), starts the lease renewal for the run (:517-521), invokes the job on a token linked to the stopping token (:515,:526), and stops and awaits the renewal before the stamp reuses the cycle context, so the two never overlap (:533-537). A run cancelled because the renewal found the lease lost is swallowed and nothing is stamped or counted, since the occurrence belongs to the replica that took the row (:528-532,:539-542). Otherwise it records duration and the outcome-tagged counter (:545-548), then computes the next occurrence from the instant execution finished, not from the occurrence that just ran (:550-554). That is the missed-run policy: a host down for a day runs each job once on startup and returns to cadence instead of replaying a backlog. The final stamp is guarded by the claim token (:563-580): a replica whose lease expired mid-execution matches nothing, logsLogLeaseLostand drops its stale outcome (:587-591) rather than overwriting the current holder's record.- The outcome stamp, retried once.
StampWithRetryAsync(:604-637) runs the stamp throughTryStampAsync(:640-653), which gives each attempt its ownCancellationTokenSource(StampTimeout, _timeProvider)(:642) rather than the host stopping token (the source calls this "the outbox M8 shape"): the doc onStampTimeout(:75-80) explains that a completed occurrence must always advance its schedule and release its lease, or a graceful stop landing between the job and the stamp would leave the row leased and re-run work that already finished once the lease expires. A failed attempt is returned rather than thrown; the first failure is logged atWarning(LogStampRetrying,:615), the runner waitsStampRetryDelayon a wait that does honor shutdown (:617-627), and tries once more (:629-633). A second failure, or a stop during the wait, is logged atError(LogStampFailed) and swallowed, returning null soExecuteClaimedJobAsyncsimply returns (:582-585,:635-636); the row then stays leased and the job runs again once the lease expires, at-least-once per ADR-074 (:596-602). Building every timer from the injectedTimeProviderkeeps both budgets testable on a fake clock. RenewLeaseWhileRunningAsync(:667-713) keeps the claim alive while the job runs: every half lease (:674) it pushesLockedUntilout by a full lease, guarded by the claim token (:684-688). A renewal that matches no row means another replica owns the row, so it logsLogLeaseLostWhileRunningand cancels the job (:690-695); a failed renewal is logged and retried after a quarter of that interval, well before the lease runs out (:675,:703-711). A replica that dies stops renewing and its lease expires as before (:660).InvokeJobAsync(:720-755) resolves the job in a fresh DI scope (:724-726), exactly like a request, so a job body gets scoped services (a unit of work, repositories, handlers) and the long-lived runner never captures a scoped dependency. A missing job returnsSkippedwith a message (:728-732); a cancellation (host shutdown or a lost lease, since the token is linked to both) is rethrown, so on shutdown the row stays leased and the occurrence is retried when the lease expires rather than being recorded as a failure it never was (:740-747); any other exception is logged and recorded asFailedwith the message fromExceptionChain.Describe(:748-754), so the schedule still advances and a permanently failing job cannot hot-loop. The two shutdown paths are deliberately different: a job interrupted mid-run is retried, while a job that ran to completion gets its stamp underStampTimeoutregardless of the stopping token.- Log levels are a cost decision. The per-occurrence start and completion lines are
Debug(:781-785) with the reason stated inline (a busy schedule would otherwise double this runner's steady-state log volume,[Rubric §31, Cost/FinOps],:778-780), while every failure line staysErrororWarning(:787-806).
- State and constants.
Why it's built this way: ADR-074 records the decision to extend the durable polling loop already in production instead of adopting Hangfire or Quartz.NET, on the grounds that the missing piece was a cron expression, not a product, and that every extracted service host (ADR-008) would otherwise have to reason about a new dependency. Cron parsing is the one thing bought rather than built (Cronos, MIT, zero-dependency).
Where it's used: registered by
AddScheduledJobsthroughTryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, ScheduledJobRunner>())(MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:47-48), deliberately notAddHostedService, since the latter appends a descriptor per call and two modules calling it would run two runners racing for the same rows (DependencyInjection.Jobs.cs:44-46). The framework's own scheduled job isAuditTrailCleanupJob, registered byAddAuditTrail(DependencyInjection.Jobs.cs:132).ScheduledJobRunnerTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/ScheduledJobRunnerTests.cs:21) drives whole cycles through the internal entry point via a sharedSchedulerTestHarness(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/SchedulerTestHarness.cs),ScheduledJobRunnerStampRetryTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/ScheduledJobRunnerStampRetryTests.cs:18) covers the stamp retry,ScheduledJobRunnerLeaseRenewalTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/ScheduledJobRunnerLeaseRenewalTests.cs:19) covers the lease renewal, andSchedulerModelGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/SchedulerModelGateTests.cs:25) pins the model gate.Caveats / not-in-source: which hosts actually call
AddScheduledJobsand setScheduler:Enabledlives in the downstream apps, not in this repository, so the set of deployments running a schedule today is Not determinable from source here.
PeriodicBackgroundService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Hosting.Background·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Hosting/Background/PeriodicBackgroundService.cs:31· Level 1 · class (public abstract partial)
What it is: the base class for fixed-interval background sweeps. It contributes the things a hand-written
BackgroundServiceloop usually gets wrong: an enablement gate evaluated once at startup, a startup delay so the host finishes initializing first, a loop whose cycle failures are logged (through an overridable hook) without killing the loop, and every wait routed through an injectedTimeProviderso a test can drive it with a fake clock (PeriodicBackgroundService.cs:8-13). On top of that it offers an opt-in cross-replica guard: a subclass that returns aCycleLockruns each cycle on one replica per interval (PeriodicBackgroundService.cs:19-27).Depends on:
Microsoft.Extensions.Hosting.BackgroundServiceas the base,TimeProviderandILoggeras its two primary-constructor parameters (PeriodicBackgroundService.cs:31-33),IDistributedLockas the type of the optionalCycleLock(:55), its private nestedCycleTurnfor the hold on that lock (:149), and theLoggerMessagesource generator for its four log methods (:212-222), which is what makes the classpartial.Concept introduced, the template method with an injected clock.
[Rubric §2, Design Patterns]assesses whether a pattern is used where it carries its weight, and this is a textbook template method: the base owns the invariant algorithm (gate, delay, take the turn, run, catch, wait) and the subclass supplies only the variable parts throughInterval,IsEnabled,StartupDelay,CycleLock,CycleLockKey,LogCycleFailure, andExecuteCycleAsync.[Rubric §29, Resilience and Business Continuity]assesses whether a background component survives its own failures: the broadcatchat:126-131, under aCA1031suppression whose justification reads "One failed cycle must not stop the background service for the life of the process" (:126), is the whole answer, because an unhandled exception insideExecuteAsyncsilently ends a hosted service for the lifetime of the process, and a reconciliation sweep that stops running is a failure nobody notices until the data is wrong. The same section applies to the lock: an unreachable lock store runs the cycle anyway (fail open), which the class doc limits to idempotent work, "where a duplicate sweep costs time, never correctness" (:24-26).[Rubric §13, Observability & Operability]assesses whether an override can keep its own event id:LogCycleFailureis virtual (:73-74) precisely so a subclass can log its own message and event id (for a dashboard that keys on it) while still relying on the base loop to call it.[Rubric §14, Testability]assesses whether time-dependent code can be tested without waiting:Task.Delay(..., timeProvider, ...)(:91,:135) means aFakeTimeProvideradvances the loop instantly, which is whatPeriodicBackgroundServiceTestsand itsFakeClockLoophelper rely on (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/PeriodicBackgroundServiceTests.cs,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/FakeClockLoop.cs).Walkthrough
Intervalis abstract (PeriodicBackgroundService.cs:36): every subclass must state its own cadence, and nothing defaults it. It is also the lock's time-to-live when aCycleLockis set (:165).StartupDelayis virtual with a 15 second default (PeriodicBackgroundService.cs:42). The doc says why it exists: let the application finish initializing before background work competes with it, and tests override it to shorten the wait (:38-41).IsEnabledis virtual and defaults totrue(PeriodicBackgroundService.cs:49). It is read once, at the top ofExecuteAsync, and afalselogs and returns (:83-87), so the service occupies no thread and no timer for the rest of the process. Flipping the toggle at runtime does not restart it.CycleLockis virtual and defaults tonull(PeriodicBackgroundService.cs:55), which runs the sweep on every replica.CycleLockKey(:62-63) defaults toperiodic-sweep:{entry assembly name}:{type full name}, with the host name falling back to the app domain's friendly name (:65-66), so replicas of one service share the key while two services sharing one lock store never take each other's turn (:57-61).LogCycleFailure(exception)is virtual (PeriodicBackgroundService.cs:73-74): the default writes one generic Error naming the service through the generatedLogCycleError. The doc comment spells out why it is overridable: a subclass can keep its own message and its own event id, which dashboards and tests key on (:68-71).ExecuteCycleAsync(stoppingToken)is the abstract single sweep (PeriodicBackgroundService.cs:78), and its contract is stated in the doc comment: exceptions are logged and do not stop the loop.ExecuteAsync(PeriodicBackgroundService.cs:81-108) is the entry point. The startup delay is wrapped in its owntrywhosecatch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)returns cleanly (:89-96), so a host stopped during the delay does not log a shutdown as an error. It then creates oneCycleTurnand runsRunLoopAsyncinside atry/finallythat releases the turn on the way out, handing it over at once on shutdown rather than leaving it to the lock's expiry (:98-107).RunLoopAsync(PeriodicBackgroundService.cs:110-142) is the loop. It runs until cancellation (:112), asks the turn whether this replica runs the cycle and only then awaitsExecuteCycleAsync(:116-119), breaks on a shutdown cancellation (:121-125), routes any other exception throughLogCycleFailure(:126-131), and waits the interval under the same cancellation-aware guard (:133-140).- The four
[LoggerMessage]methods (PeriodicBackgroundService.cs:212-222) are source-generated:LogCycleSkippedat Debug,LogCycleLockUnavailableat Warning with the exception,LogDisabledat Information, andLogCycleErrorat Error with the exception attached and a message that states the recovery ("it will retry on the next interval"). All four stampGetType().Name, so the log line names the concrete sweep, not the base class;LogCycleErroris called throughLogCycleFailurerather than directly from the loop, and the two lock messages are written byCycleTurnthrough the privateLoggeraccessor (:210).
Why it's built this way: the class doc draws the boundary explicitly (
PeriodicBackgroundService.cs:14-18): this is for periodic reconciliation and cleanup work, and it is deliberately not what the outbox processor uses, because the outbox's signal-driven smart wait does not fit a fixed interval. The background-work posture is ADR-052, and a fixed-interval sweep is a different thing again from the cron-style recurring scheduler of ADR-074, which is why this base stays as small as it is. The replica guard is opt-in with anulldefault so a sweep that is not idempotent, or a host with no lock, keeps the plain every-replica behavior (:51-55).Where it's used: six framework sweeps derive from it: PermissionGrantRefreshService (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PermissionGrantRefreshService.cs:36), RefreshSessionCleanupService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionCleanupService.cs:59), InternalCommandCleanupService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandCleanupService.cs:52), OutboxCleanupService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxCleanupService.cs:58), NotificationCleanupService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationCleanupService.cs:52) and PostgreSqlDeadLetterCleanupService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlDeadLetterCleanupService.cs:20). All of them exceptPermissionGrantRefreshServiceoverrideCycleLock(RefreshSessionCleanupService.cs:72,InternalCommandCleanupService.cs:65,OutboxCleanupService.cs:85,NotificationCleanupService.cs:68,PostgreSqlDeadLetterCleanupService.cs:63). ScheduledJobRunner is the closest relative and deliberately is not a subclass: it derivesBackgroundServicedirectly and only names this class in a comment (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobRunner.cs).Caveats / not-in-source: cross-replica coordination exists only when a subclass returns a
CycleLock; the default runs the sweep on every replica. The lock is taken with a time-to-live of oneIntervaland no wait (:165), and it fails open, so it reduces duplicate sweeps rather than forbidding them. Whether a cycle that runs longer than itsIntervalcan overlap another replica's depends on theIDistributedLockimplementation's expiry behavior, which is not determinable from this source. Contrast ScheduledJobRunner, which coordinates replicas with a database claim lease.
CycleTurn
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Hosting.Background·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Hosting/Background/PeriodicBackgroundService.cs:149· Level 1 · class (private sealed, nested in PeriodicBackgroundService)
What it is: one replica's hold on a
PeriodicBackgroundService'sCycleLock. It is released and re-taken at the start of each cycle, so the holder keeps the turn while it lives and the lock's time-to-live hands the turn over when it does not (PeriodicBackgroundService.cs:144-148).Depends on: its owning service, passed as the one primary-constructor parameter (
PeriodicBackgroundService.cs:149), forCycleLock,CycleLockKey,Intervaland the privateLogger(:156,:165,:210);IDistributedLock.TryAcquireAsyncfor the take;IAsyncDisposableas the held handle (:151);Interlockedfor the release (:192).Concept introduced, a turn that is kept, not re-won.
[Rubric §29, Resilience and Business Continuity]assesses whether coordination degrades safely. The holder releases its own hold immediately before re-taking it (:161), so on a healthy replica the next cycle normally finds the key free and keeps the turn; another replica that wakes inside the interval finds it held and skips. A replica that dies stops renewing, and the time-to-live of oneIntervalfrees the key for the others. Both failure paths fail open: a lock store that throws runs the cycle anyway (:172-178), and a release that throws is only logged, because the lock expires on its own (:201-206).[Rubric §13, Observability & Operability]: a skip is a Debug line and an unreachable lock a Warning, both naming the concrete service (:182,:176,:205).Walkthrough
_held(PeriodicBackgroundService.cs:151): the current hold, or null.TryTakeAsync(stoppingToken)(:154-187): with noCycleLockit returnstrueat once (:156-159), so the no-lock default costs nothing. Otherwise it releases any previous hold (:161) and callsTryAcquireAsync(CycleLockKey, Interval, TimeSpan.Zero, stoppingToken)(:164-166): a time-to-live of one interval and no wait. A shutdown cancellation propagates (:168-171); any other exception logsLogCycleLockUnavailableand returnstrue(:172-178). A null handle means another replica holds the turn: it logsLogCycleSkippedand returnsfalse(:180-184).ReleaseAsync()(:190-207): swaps_heldto null withInterlocked.Exchangeand returns when there was nothing held (:192-195), so a double release is harmless; it disposes the handle and logs, never throws, on a failure (:197-206).
Why it's built this way: keeping the hold in a small object owned by
ExecuteAsynclets the base release it in onefinallyon shutdown (PeriodicBackgroundService.cs:98-107), while the loop itself only asks one question per cycle,TryTakeAsync(:116).Where it's used: created once per run by
PeriodicBackgroundService.ExecuteAsync(PeriodicBackgroundService.cs:98) and consulted byRunLoopAsync(:116); it has no use outside the defining file.Caveats / not-in-source: the turn is only as exclusive as the registered
IDistributedLockimplementation; which implementation a host runs is decided by registration, not here.
ChannelJoinAuthorizerMissingWarningService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/ChannelJoinAuthorizerMissingWarningService.cs:16· Level 1 · class (internal, sealed, partial, IHostedService)
What it is: a one-shot startup check. When push notifications are registered and no
IChannelJoinAuthorizeris, it logs one Warning saying that the notification hub then refuses every channel join, failing closed (ChannelJoinAuthorizerMissingWarningService.cs:8-13). It changes no join behavior; it only makes the refusal visible at startup rather than on the first refused join.Depends on:
IServiceProviderIsServiceandILogger<ChannelJoinAuthorizerMissingWarningService>as primary-constructor parameters, implementingIHostedService(:16-18). The check namesIChannelJoinAuthorizer, and the refusal it describes is enforced byNotificationHub(:10-11). Externals:Microsoft.Extensions.DependencyInjection,.Hosting,.Logging(:1-3).Concept introduced: fail closed, and say so at startup.
[Rubric §11, Security]assesses whether the default posture is the safe one and whether it is explicit. Without an authorizer the hub refuses every channel join, so a host that forgot to register one leaks nothing; the framework still does not refuse to boot, because a host that uses no live channels needs no authorizer. It states the consequence once, at startup, in a message that names the interface to register and tells the operator to register one if the host uses live channels (:36-39).[Rubric §13, Observability & Operability]: the warning lands in the startup log where an operator reviewing a new deployment sees it, rather than surfacing only as a client's first refused join.Walkthrough:
StartAsync(:21-31): asksIServiceProviderIsService.IsService(typeof(IChannelJoinAuthorizer))(:25), which answers without resolving an instance, and logsLogNoChannelJoinAuthorizerwhen the answer is no (:27). The check runs at start, not at registration, because a host may register its authorizer after callingAddPushNotifications(:23-24).StopAsync(:34): a no-op.LogNoChannelJoinAuthorizer(:36-39): a source-generated[LoggerMessage]atWarning.
Why it's built this way: a hosted service is the one place that runs after the whole container is built, so it sees every registration regardless of call order. Push notifications and their channel model are described in ADR-024.
Where it's used: registered by
AddPushNotificationswithAddHostedService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:107); the comment there notes thatAddHostedServiceis aTryAddEnumerable, so a second call adds no second warning (:105-106).
ConnectionChannels
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:248· Level 2 · class (private sealed, nested in NotificationHub)
What it is: one SignalR connection's channel memberships and channel-join budget inside
NotificationHub. It is locked, because a host may allow a client parallel hub invocations (NotificationHub.cs:244-247), and it lives in the connection'sContext.Itemsbag, so it ends with the connection (:32,:196-206).Depends on:
PushNotificationSettingsforChannelJoinsPerMinuteandChannelJoinBurst(NotificationHub.cs:258,:265,:273);System.Threading.Lockas the gate and an ordinalHashSet<string>of joined channel keys (:250-251).Concept introduced, bounding a connection on two axes.
[Rubric §11, Security]assesses whether an authenticated caller can exhaust a shared resource. The hub's remarks name the two bounds,MaxChannelsPerConnectionandChannelJoinsPerMinutewithChannelJoinBurst, and state why the join budget is spent before any other check: a refused join then costs the same as an accepted one, so a loop of refused joins cannot drive the entitlement check without bound (NotificationHub.cs:27-33).[Rubric §12, Performance & Scalability]: the budget is a token bucket refilled lazily on each call, so there is no timer per connection.Walkthrough
- State (
NotificationHub.cs:250-253): the_gatelock, the_joinedset,_tokensstarting at-1(meaning "not yet filled") and_refilledAt. TrySpendJoin(settings, now)(:256-285): always succeeds whenChannelJoinsPerMinute <= 0, the limit being off (:258-261). Under the lock the first call fills the bucket toChannelJoinBurst(:266-269); later calls add the elapsed minutes times the per-minute rate, capped at the burst (:272-273). It stamps_refilledAt(:276), refuses below one token (:277-280), and otherwise spends one (:282-283).TryReserve(channelKey, cap, out reserved)(:291-309): a channel already joined succeeds withreserved = false, so a failed re-join does not give back a slot it did not take (:287-290,:296-299); a positivecapthat is already reached refuses (:301-304); otherwise it adds the key and reportsreserved = true(:306-307).Release(channelKey)(:312-318): removes the key under the lock.
- State (
Why it's built this way:
JoinChannelAsyncspends the budget first (NotificationHub.cs:148-152), validates the key shape (:154), then reserves the slot before the entitlement check so two concurrent joins on one connection cannot both take the last slot (:156-161), and gives the slot back only when this call reserved it and the join did not complete (:173-177). Keeping that state per connection, behind one lock, is what makes the reserve-then-check order safe.Where it's used: only inside
NotificationHub:ChannelsOfConnection()creates it on a connection's first join or leave and stores it under themmca.hub.channelsitem key (NotificationHub.cs:57,:196-206);JoinChannelAsyncspends, reserves and releases (:145-177);LeaveChannelAsyncreleases after removing the group membership (:192).Caveats / not-in-source: the budget and the cap are per connection, so a user with several connections gets one budget each; the per-user connection cap is a separate static count in the hub (
NotificationHub.cs:64-73). The default values of the three settings live onPushNotificationSettings, not here.
IBrokerMessageConsumer
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IBrokerMessageConsumer.cs:12· Level 2 · interface (internal)
- What it is: the non-generic entry point the receive pipeline dispatches a deserialized event through. Its one member,
ConsumeAsync(IIntegrationEvent, IReadOnlyDictionary<string, string> headers, CancellationToken)(IBrokerMessageConsumer.cs:19), letsBrokerReceivePipelinecall the closed consumer for a subscription's runtime type without reflection per message (IBrokerMessageConsumer.cs:5-11). - Depends on:
IIntegrationEventand the BCL only. The headers arrive as a plain string dictionary, so nothing broker-specific crosses this boundary. - Concept introduced, a typed consumer behind a non-generic door.
[Rubric §10, Messaging & Integration Architecture]assesses whether the consume path is independent of the transport. The pipeline only learns the event's CLR type at run time (from the event-name header), so it cannot call a genericConsumeAsync<TEvent>directly. Both consumers implement this interface explicitly and forward to their own typed method with one cast, so the typed API stays the public face and the pipeline resolves the consumer once per attempt as(IBrokerMessageConsumer)scope.ServiceProvider.GetRequiredService(consumerType)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:260). - Walkthrough
ConsumeAsync(integrationEvent, headers, cancellationToken)(IBrokerMessageConsumer.cs:19): the task completes when every handler has run and faults when one failed (:18); that fault is what drives the pipeline's retry.
- Where it's used: implemented by
IntegrationEventConsumer<TEvent>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:44, explicit forward at:138) andUpcastingIntegrationEventConsumer<TEvent>(UpcastingIntegrationEventConsumer.cs:34, explicit forward at:140-144); called byBrokerReceivePipeline.
ConsumerOriginRestore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/ConsumerOriginRestore.cs:20· Level 6 · class (internal static)
- What it is: the consumer-side half of context propagation. It reads the five origin headers off a delivered message and restores them onto the per-message scope through
AmbientOrigin.Restore, so a broker-delivered handler sees the identity, tenant and correlation id an in-process dispatch would have seen; a message carrying no headers (an older publisher, or an event raised with no user) leaves the scope's defaults untouched (ConsumerOriginRestore.cs:7-12,:22-26). - Depends on:
AmbientOriginfor the actual restore,MessageHeadersfor the five header names,IServiceProvider, and theUserIdentifierTypealias with itsTryParse. The headers arrive as anIReadOnlyDictionary<string, string>(:31), the transport-neutral shape every transport hands the receive pipeline. - Concept introduced, parsing rather than trusting a typed header.
[Rubric §10, Messaging & Integration Architecture]assesses whether the pipeline handles transport differences correctly rather than assuming one broker's behavior. The user id is transported as text and parsed back withUserIdentifierType.TryParseunder the invariant culture (ConsumerOriginRestore.cs:37-43). A malformed value is treated as a publisher bug, not a reason to fail the consume, so it simply yields no identity rather than throwing (:35-36). - Walkthrough
Apply(headers, services, authenticationType)(ConsumerOriginRestore.cs:31-53) throws on nullheaders(:33), parsesMessageHeaders.UserId, defaulting to null on failure (:37-43), and returns anIDisposable: the handle that withdraws the published origin, which the caller holds for the whole consume (:30).- It returns
AmbientOrigin.Restorewith that id and the remaining four headers,UserRoles,UserPermissions,TenantId, andCorrelationId, read straight through as strings (ConsumerOriginRestore.cs:45-52), so the handle isAmbientOrigin's own restore handle passed through unchanged. Get(headers, name)(:55-56):TryGetValue, null when the header is absent.
- Why it's built this way: keeping the header-reading and the id-parsing in this one adapter, separate from
AmbientOriginitself, means the restore logic stays transport-agnostic while this class is the one step of the restore that knows about a transport (ConsumerOriginRestore.cs:14-18). - Where it's used: called by
IntegrationEventConsumer<TEvent>andUpcastingIntegrationEventConsumer<TEvent>(UpcastingIntegrationEventConsumer.cs:65), the two consumersBrokerReceivePipelinedispatches to, both before touching the inbox, so a retired contract is restored under the same identity and tenant its plain-consumer sibling would have used. Also referenced byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/BrokerMessageBusTests.cs.
EventUpcasterStartupValidator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/EventUpcasterStartupValidator.cs:20· Level 3 · class (internal sealed)
- What it is: a one-method
IHostedServicewhose entire job is to resolveIEventUpcasterRegistryat host start, so a bad upcaster registration graph fails the host instead of dead-lettering the first retired-contract message hours later (EventUpcasterStartupValidator.cs:7-12). - Depends on:
IEventUpcasterRegistryas its single primary-constructor parameter (EventUpcasterStartupValidator.cs:20),Microsoft.Extensions.Hosting.IHostedService, andIIntegrationEventas the type it probes with. - Concept introduced, validation by construction, forced by resolution.
[Rubric §15, Best Practices and Code Quality]assesses whether invariants are checked at the earliest possible moment, and[Rubric §13, Observability and Operability]assesses whether a misconfiguration is discoverable. The validation itself does not live here:EventUpcasterRegistryvalidates its whole registration graph in its constructor, rejecting a duplicate source, a type mapped onto itself, and a cycle, with a message naming the offenders. Since DI is lazy, that constructor might not run until the first broker message arrives. This class exists purely to make it run at start. That is the fail-fast configuration posture of ADR-070 applied to a graph that options validation cannot express. - Walkthrough
StartAsync(EventUpcasterStartupValidator.cs:23-30) discards the result ofupcasters.ResolveTerminalType(typeof(IIntegrationEvent))(:27) and returns a completed task. The comment at:25-26explains why the call exists at all: the real work happened in the injected registry's constructor, and reading one member is what makes the dependency impossible to elide.StopAsync(EventUpcasterStartupValidator.cs:33) is a completed task. There is nothing to unwind.
- Why it's built this way: the registration is the other half of the design, and its comment is explicit (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:258-263):TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, EventUpcasterStartupValidator>()), notAddHostedService, because two modules callingAddInfrastructuremust not run the same validation twice.TryAddEnumerablede-duplicates on the implementation type, whichAddHostedServicedoes not. The class doc adds the cost note (EventUpcasterStartupValidator.cs:13-17): a host with no upcasters resolves an empty registry, and the whole mechanism costs one no-op call at start (ADR-090). - Where it's used: registered once inside
AddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:262-263), so every host that calls it gets the check. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Consumers/EventUpcasterStartupValidatorTests.cs.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
UpcastDispatch
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastDispatch.cs:15· Level 3 · class (internal static)
- What it is: the dispatch cache behind
UpcastingIntegrationEventConsumer<TEvent>. Per terminal event type it memoizes the closedIIntegrationEventHandler<in TIntegrationEvent>interface and a compiled invoker for itsHandleAsync(UpcastDispatch.cs:7-14). - Depends on:
IIntegrationEventHandler<in TIntegrationEvent>; externalsSystem.Collections.ConcurrentandSystem.Linq.Expressions(UpcastDispatch.cs:1-2). - Concept: the compiled-invoker technique
DomainEventDispatcheruses for the in-process path, applied to the broker path.[Rubric §12, Performance & Scalability]assesses whether per-message cost stays flat. The terminal type is only known at run time, because it depends on which upcasters the host registered, so handler resolution is non-generic; compiling an expression once per type keeps reflection off the per-message path. The class is non-generic on purpose, so every closed consumer type shares one cache instead of eachUpcastingIntegrationEventConsumer<TEvent>closure holding its own (UpcastDispatch.cs:12-13). - Walkthrough
Cache(UpcastDispatch.cs:17-19): aConcurrentDictionary<Type, (Type ClosedHandlerType, Func<object, object, CancellationToken, Task> Invoker)>.For(Type terminalType)(UpcastDispatch.cs:24-29):GetOrAddwith astaticfactory that closesIIntegrationEventHandler<>over the type and callsBuildInvoker.BuildInvoker(Type eventType)(UpcastDispatch.cs:39-59): looks upHandleAsyncon the closed interface, throwingInvalidOperationExceptionif it is missing (:42-43), then builds(object handler, object integrationEvent, CancellationToken ct) => ((IIntegrationEventHandler<T>)handler).HandleAsync((T)integrationEvent, ct)as an expression tree and compiles it (:57-58).
- Why it's built this way: a static field on the generic consumer would be one field per closed type; a separate non-generic class is what lets the cache be shared across every closed consumer type, as the class doc states (
UpcastDispatch.cs:12-13). - Where it's used: one call,
UpcastDispatch.For(terminalType)inUpcastingIntegrationEventConsumer<TEvent>.ConsumeAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastingIntegrationEventConsumer.cs:90).
UserEmailResources
MMCA.Common.Application ·
MMCA.Common.Application.Users.Emails·MMCA.Common/Source/Core/MMCA.Common.Application/Users/Emails/UserEmailResources.cs:15· Level 4 · class (internal static)
- What it is: the localization helper behind the default account emails (forgot-password, email-confirmation and sign-in link,
UserEmailResources.cs:9). It looks up subject and body text from a.resxset by key, formats the one/other plural form of the code- or link-lifetime sentence, and can run the composition of an email under the recipient's stored culture (UserEmailResources.cs:15,:29,:50-52,:64-65). - Depends on:
System.Resources.ResourceManagerbound to the class's own resource set (:17),IUserPreferences.PreferredCultureto read the recipient's stored language, andSupportedCultures.ResolveClosestto map it to the nearest supported culture (:34). - Concept introduced, the email is written in the recipient's language, not the requester's. Text that leaves the request (an email sent to someone else's address) should honor that person's locale.
InRecipientCulture<T>(recipient, compose)(UserEmailResources.cs:29-44) savesCultureInfo.CurrentUICulture, switches it to the recipient's resolved preference whenrecipientis anIUserPreferenceswith a non-blankPreferredCulture, runscompose, and restores the previous culture in afinally. Without a stored preference the request's culture stays in force. Because it sets the current UI culture, both the default.resxtext and any app override that reads the current UI culture speak the recipient's language. - Walkthrough
InRecipientCulture<T>(object recipient, Func<T> compose)(:29-44): the culture scope described above.Get(key)(:50-52):ResourceManager.GetStringin the current UI culture, falling back to the neutral English text when a translation is missing, and throwingInvalidOperationExceptionnaming the key when the key itself is absent.Plural(key, count, params args)(:64-65): picks{key}.Onewhencount == 1and{key}.Otherotherwise, then formats with the invariant culture. It applies the same one/other splitStringLocalizerPluralExtensionsapplies to the UI resources (ADR-027).
- Why it's built this way: the account email handlers are framework base classes, so their default copy has to be translatable without each app shipping its own resources; keeping the helper
internal statickeeps the key vocabulary private to the three handler bases while apps overrideComposeSubjectand the body builders when they want their own text. - Where it's used:
ForgotPasswordHandlerBase(ForgotPasswordHandlerBase.cs:133-135,:148,:163-168; see ADR-091),SendEmailConfirmationHandlerBase(SendEmailConfirmationHandlerBase.cs:143-145,:168,:183-188) andSendSignInLinkHandlerBase(SendSignInLinkHandlerBase.cs:142,:172,:183-186), all three underMMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases. - Caveats / not-in-source: the
.resxkey list and the set of supported cultures are not read here; whether every key has a translation in every supported culture is not determinable from this source.
NotificationCleanupService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationCleanupService.cs:46· Level 10 · class (internal, sealed, partial, PeriodicBackgroundService)
What it is: the retention sweep for notifications. On each interval it soft-deletes every inbox row (
UserNotification) created beforeNotificationSettings.RetentionDaysago, then every sent notification (PushNotification) created before that cutoff that no live inbox row still points at (NotificationCleanupService.cs:17-21).Depends on: five primary-constructor parameters,
IServiceScopeFactory,ILogger<NotificationCleanupService>,IOptions<NotificationSettings>,TimeProviderand an optionalIDistributedLock(cycleLock, defaultnull), and derives fromPeriodicBackgroundService(:46-52). Per sweep it resolvesIEntityDataSourceRegistryandIDbContextFactoryfrom a fresh scope (:112,:119). Externals: EF Core (ExecuteUpdateAsync),Microsoft.Extensions.*andSystem.Linq.Expressions(:1-5).Concept introduced: retention by soft delete, batched.
[Rubric §8, Data Architecture]assesses whether data has a lifecycle. The sibling sweeps (outbox, internal commands, refresh sessions, audit trail) hard-delete framework bookkeeping rows, but both notification tables are auditable aggregates, so this sweep setsIsDeletedandDeletedOninstead: the rows leave every inbox, unread count and history read without being erased from audit and erasure accounting (:23-29).[Rubric §12, Performance & Scalability]assesses whether background work stays bounded.SoftDeleteAsyncreads at mostBatchSize(1000,:55) ids in key order and retires them by id in oneExecuteUpdateAsync, looping until a short batch, so a first sweep over a long-neglected table is many short statements rather than one long one (:175-214). The inbox rows go first, so a notification is retired only once nothing visible refers to it (:151-164). The same section covers the replicas: the purge is idempotent, so with a lock it runs on one replica per interval rather than once per replica, and the override's remark notes thatAddInfrastructurealways registers one (:63-68).[Rubric §13, Observability & Operability]: the purge counts are logged on every sweep, zero included, because the line is the operator's evidence that retention runs (:127-129).Walkthrough:
BatchSize(:55),_settings(:57) and_timeProvider(:61, captured separately because the base constructor already receives the parameter, CS9107,:59-60).CycleLock(:68): returns the injectedcycleLock, so the base's one-replica-per-interval guard is on whenever DI supplies a lock and off (every replica sweeps) when it does not.Interval(:71):CleanupIntervalHoursfrom settings;StartupDelay(:77): one full interval, so the first sweep never competes with startup or migration work (:73-76).IsEnabled(:80-94): false, with an Information line, whenRetentionEnabledis off. A second check behind the registration gate, so a host that registers the service by hand stays honest.ExecuteCycleAsync(:97) runsPurgeAsync;LogCycleFailure(:100) logs atError.PurgeAsync(:106-130, internal for tests): computes the cutoff (:109); resolves theUserNotificationsource key from the registry and the context for it, returning with a Warning when the key is unknown or either entity is missing from that context's model (:112-125); then callsRetireAsyncand logs the counts (:128-129).RetireAsync(:144-167, internal static): inbox rows older than the cutoff (:151-156), then notifications older than the cutoff with no live inbox row (!liveInbox.Any(u => u.PushNotificationId == p.Id),:161).SoftDeleteAsync<TEntity>(:175-214, private): constrained toAuditableBaseEntity<int>(:181); observes cancellation between batches (:184); the soft-delete query filter keeps already-retired rows out of every batch (:169-174).
Why it's built this way: both tables live in the
Notificationlogical database, so one sweep resolves one physical source through the entity registry, the same way the refresh-session sweep does (:31-36). Deriving fromPeriodicBackgroundServicekeeps the loop, the delay, the failure handling and the replica guard in one shared base, leaving this class only the sweep and the choice to opt into the lock.Where it's used: registered by
AddNotificationInfrastructurewithAddHostedServiceonly whenNotifications:RetentionEnabledis set (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:45-47, comment:43-44). Pinned byNotificationCleanupServiceTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Notifications/NotificationCleanupServiceTests.cs:26), which drivePurgeAsyncandRetireAsyncdirectly.Caveats: the default values of
RetentionDaysandCleanupIntervalHourslive onNotificationSettings, not here; read them there. A host whose model maps neither notification table gets a Warning per sweep and nothing is deleted.
InboxHandlerLoop
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/InboxHandlerLoop.cs:21· Level 11 · class (internal static partial)
- What it is: the per-handler consume loop both broker consumers share,
IntegrationEventConsumer<TEvent>andUpcastingIntegrationEventConsumer<TEvent>, so the inbox rule lives in one place (InboxHandlerLoop.cs:7-9). - Depends on:
IInboxStore(GetProcessedConsumersAsyncandRecordAsync),EfInboxStorefor itsLegacyConsumermarker (InboxHandlerLoop.cs:61;MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/EfInboxStore.cs:45),InboxConsumerfor the per-handler consumer name,InboxConsumeScopefor the ambient marker a handler runs inside, andMicrosoft.Extensions.Loggingfor its two source-generated log methods (InboxHandlerLoop.cs:1-3). - Concept introduced, the inbox keyed per handler, not per message.
[Rubric §10, Messaging & Integration Architecture]assesses whether at-least-once delivery is made safe at the consumer, and ADR-021 is the decision. A message fans out to every registered handler, and they can fail independently. The class doc (InboxHandlerLoop.cs:10-19) states the consequence of the earlier message-wide key: a redelivery either re-ran the handlers that had already succeeded or, once an earlier handler's save had committed the message-wide row, skipped the failed handler forever. Keying the row on (message id, handler) means a retry runs only the failed handler and the ones after it, while the handlers before it stay recorded.[Rubric §12, Performance & Scalability]: the recorded handlers are read once per message rather than once per handler (:45-48). - Walkthrough
RunAsync<THandler>(inbox, messageId, eventTypeName, handlers, invoke, logger, cancellationToken)(InboxHandlerLoop.cs:33-83) is the one entry point.THandleris constrained toclass(:41), and the handler is invoked through the caller-suppliedinvokedelegate, which is what lets the typed consumer and the reflection-free upcast path (anobjecthandler plus a compiled invoker fromUpcastDispatch) share the same loop.- The
processedset starts null (InboxHandlerLoop.cs:51). For each handler, in registration order, it counts the handler and computes its inbox consumer name withInboxConsumer.NameOf(handler.GetType())(:55-56); the first handler fills the set with oneinbox.GetProcessedConsumersAsync(messageId, ...)read under ordinal comparison (:57-59), so a message with no handler touches no inbox (:45-47). - A handler whose name is in the set, or any handler when the set holds
EfInboxStore.LegacyConsumer(a legacy message-wide row), logs at Debug and is skipped (InboxHandlerLoop.cs:61-65). The comment notes the set is empty when the inbox is disabled, so every handler runs as it would without an inbox (:48-49). - Otherwise
InboxConsumeScope.Enter(messageId, consumer)opens the marker that lets aScopedIntegrationEventHandlerBase<TIntegrationEvent>handler stage its own row atomically with its writes (InboxHandlerLoop.cs:69,:13-14). The marker spans the record too, because the store reads it to learn whether the handler staged its own row or the row must simply be inserted (:67-68). - Inside the marker,
InvokeAsync(InboxHandlerLoop.cs:85-106) runs the delegate; a throw other thanOperationCanceledExceptionis logged at Error with the handler's full type name and rethrown (:97-105). Nothing is recorded for that handler, so the receive pipeline's retry in a fresh scope (BrokerReceivePipeline, bounded byMessageBusSettings.RetryLimit, default5atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:94) runs it again. - On success,
inbox.RecordAsync(messageId, eventTypeName, consumer, ...)writes the row, still inside the marker (InboxHandlerLoop.cs:76). It absorbs the row a scoped handler already committed with its own save and writes it for every other handler (:73-75); the store contract makes that idempotent (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/IInboxStore.cs:30-41). - The consumer name is then added to the local set (
InboxHandlerLoop.cs:79), so a handler type registered twice still runs once per message (:49-50). - It returns the number of registered handlers, run or skipped (
InboxHandlerLoop.cs:82), so the caller can log the zero-handler case itself.
- Why it's built this way: two consumers that each carried their own copy of the skip, run, record and rethrow sequence would let the inbox rule drift between the current-contract and retired-contract paths. Extracting it into an internal static helper that takes the handler set and an invoke delegate keeps one implementation of the rule while each consumer keeps its own handler resolution.
- Where it's used: called once from each consumer,
IntegrationEventConsumer<TEvent>.ConsumeAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumer.cs:83) andUpcastingIntegrationEventConsumer<TEvent>.ConsumeAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastingIntegrationEventConsumer.cs:92-99). It has no test class of its own; the per-handler skip and record behavior is asserted through the consumers inMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Consumers/IntegrationEventConsumerTests.csandUpcastingIntegrationEventConsumerTests.cs. - Caveats / not-in-source: a crash after a handler returns but before
RecordAsynccompletes redelivers the message to that handler, which is why handlers must still be idempotent (InboxHandlerLoop.cs:73-75).
UpcastingIntegrationEventConsumer<TEvent>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastingIntegrationEventConsumer.cs:30· Level 8 · class (public sealed partial, generic)
- What it is: the draining consumer for a retired integration-event contract. It receives the old type from the host's queue, upcasts each message to its terminal contract, and invokes the handlers registered for that terminal contract, so handlers are written once against the newest event type while producers still publishing the old one (and messages already queued at the upgrade) keep being delivered (
UpcastingIntegrationEventConsumer.cs:10-20). - Depends on:
IEventUpcasterRegistry,IServiceProvider,IInboxStore, andILogger<T>as its four primary-constructor parameters (UpcastingIntegrationEventConsumer.cs:31-34); implementsIBrokerMessageConsumer(:34);EventNameResolverfor the inbox key;ConsumerOriginRestoreto restore the publisher's identity, tenant, and correlation id before the inbox is touched;UpcastDispatchfor the per-terminal-type handler invoker;InboxHandlerLoopfor the per-handler inbox loop. - Concept introduced, contract retirement without a coordinated deploy.
[Rubric §6, CQRS and Event-Driven]assesses whether the event pipeline can evolve its contracts, and[Rubric §7, Microservices Readiness]assesses whether two services can be deployed independently. Renaming or reshaping an integration event across a distributed system normally forces a lockstep deploy, because in-flight messages of the old shape have no handler on the other side. ADR-090 resolves that with a registeredIEventUpcasterchain plus this consumer: the old subscription stays bound and drains, each message walks the upcaster chain to the terminal type, and the handler code only ever knows the newest contract. The current contract keeps using the plainIntegrationEventConsumer<TEvent>, and the builder refuses to register both kinds for the same type (UpcastingIntegrationEventConsumer.cs:17-19; the check itself isBrokerConsumerBuilder's duplicate guard). - Concept, dedup keyed on the original message id.
[Rubric §12, Performance & Scalability]assesses whether idempotency is applied uniformly rather than per handler. Idempotent consumption (ADR-021) keys on the message id carried in the envelope. The doc (UpcastingIntegrationEventConsumer.cs:22-26) records that the registry preserves the envelope across every upcast hop, so the id this consumer records is the same id a plain consumer would have recorded, and a redelivery is recognised whatever contract the handlers ultimately see. Like the plain consumer, the key is per handler, through the sameInboxHandlerLoop(:24-25). - Concept, restoring the publisher's origin before the inbox is touched.
[Rubric §11, Security]and[Rubric §8, Data Architecture]both apply here: under database-per-tenant, the inbox store's own routing depends on the tenant this restore sets.PrincipalAuthenticationType(UpcastingIntegrationEventConsumer.cs:37-42) is declared as the same constantIntegrationEventConsumer<TEvent>uses, because an upcast changes the contract, never the hop the identity came back from.ConsumeAsynccallsConsumerOriginRestore.Apply(:60-65) before the dedup check for exactly the reason the sibling consumer does it in the same order: a retired contract is delivered with the same headers as a current one, so a consumer that skipped this would run its handlers anonymous while its sibling did not. The returned handle is bound withusing var originand so held for the whole consume (:64-65), which lets a handler's own scope inherit the origin too. - Walkthrough
ConsumeAsync(integrationEvent, headers, cancellationToken)(UpcastingIntegrationEventConsumer.cs:52-107) guards both arguments (:57-58), restores the publisher's origin first viaConsumerOriginRestore.Apply(:65), then takesintegrationEvent.MessageIdbefore any upcasting (:69), which is the point of the earlier concept paragraph on dedup.- The event name recorded on every inbox row is
EventNameResolver.GetInboxName(typeof(TEvent))(UpcastingIntegrationEventConsumer.cs:73), the retired contract's[EventName]identity when it declares one and its short type name otherwise. The comment marks it as diagnostics only (:71-72): the dedup key is the message id plus the handler, not the event name. - With no upcaster registered for the type, the consumer logs at Information and continues (
UpcastingIntegrationEventConsumer.cs:75-80). This is the documented degrade path: the registry returns the instance untouched, and handlers for the original type run as usual. UpcastToTerminalproduces the terminal instance, and a type change is logged at Debug with both contract names (UpcastingIntegrationEventConsumer.cs:82-88).- Handler dispatch is non-generic because the terminal type is only known at runtime:
UpcastDispatch.For(terminalType)(UpcastingIntegrationEventConsumer.cs:90) returns the closedIIntegrationEventHandler<>interface and a compiled invoker, memoized per terminal type inUpcastDispatch, so reflection is paid once per contract instead of once per message. This mirrors whatDomainEventDispatcherdoes for the in-process path. - The handlers resolved for the closed interface are handed to
InboxHandlerLoop.RunAsyncasobjects, with a lambda that forwards each one to the compiled invoker on the terminal event (UpcastingIntegrationEventConsumer.cs:92-99). The loop owns the per-handler skip, the run inside the inbox consume scope, the record on success, and the log-and-rethrow on failure that hands retry, redelivery or dead-lettering toBrokerReceivePipeline. This consumer no longer carries a dispatch loop, a staged message-wide row, or a handler-failure log of its own. - Zero handlers is an Information log, not an error (
UpcastingIntegrationEventConsumer.cs:101-106): returning normally completes the message, and the comment states plainly that the broker will not retry. - The explicit
IBrokerMessageConsumer.ConsumeAsync(UpcastingIntegrationEventConsumer.cs:110-114) casts the event toTEventand forwards, which is how the non-generic pipeline reaches the typed method.
- Why it's built this way: the alternative to a per-retired-type consumer is version-tolerant handlers, each branching on a schema version, which spreads the migration across every handler and never gets cleaned up. Concentrating it in one registered consumer per retired contract means the retirement is visible in one place in a host's broker registration and can be deleted when the old subscription is drained (ADR-010 sets the versioning policy, ADR-090 ships the mechanism, ADR-118 makes the transports framework code).
- Where it's used: registered per retired type through
RegisterUpcastedIntegrationEventConsumer<TEvent>on theIBrokerConsumerBuilderthatAddBrokerMessaginghands its callback (BrokerConsumerBuilder,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:25-27), which maps the subscription to this closed type (:40-42) and has it registered scoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:105). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Consumers/UpcastingIntegrationEventConsumerTests.cs. - Caveats / not-in-source: no host under
MMCA.ADC/SourcecallsRegisterUpcastedIntegrationEventConsumer(MMCA.Store was not re-checked in this pass); the extension point is documented onBaseIntegrationEventand onOutputCacheEvictionRequestedas the path to take when a contract is retired. Its behavior is therefore established by the test suite rather than by production traffic.
[Rubric §10, Messaging & Integration Architecture] applies: this type sits on the path a message takes once it leaves the process (outbox, bus, consumer, or broker plumbing), which is what section 10 scores.
BrokerConsumerBuilder
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerConsumerBuilder.cs:12· Level 9 · class (internal sealed)
- What it is: the
IBrokerConsumerBuilderthatAddBrokerMessaginghands itsconfigureConsumerscallback. It collects oneBrokerSubscriptionper registered event, in registration order, for the host'sBrokerTopology(BrokerConsumerBuilder.cs:6-10). - Depends on:
IBrokerConsumerBuilder,BrokerSubscription,BrokerConsumerKind,BrokerNamingfor the event name and topic,IIntegrationEventas the constraint, and the two consumer types it maps onto. Its one constructor argument is the resolved application namespace topics are prefixed with (:11-12). - Concept: registration as data.
[Rubric §10, Messaging & Integration Architecture]assesses whether the topology a host consumes is explicit and checkable. Instead of each registration wiring a transport directly, the builder only records(EventName, EventType, Topic, Kind)rows; the topology, the scoped consumer registrations and the receive pipeline's dispatch table are all derived from that one list, so every transport sees the same subscriptions. - Walkthrough
_subscriptionsand theSubscriptionsview (BrokerConsumerBuilder.cs:14,:17), in registration order.RegisterIntegrationEventConsumer<TEvent>()(:20-22) andRegisterUpcastedIntegrationEventConsumer<TEvent>()(:25-27) both callAddwithBrokerConsumerKind.CurrentorBrokerConsumerKind.Upcasted, and return the builder for chaining.ConsumerTypeFor(subscription)(:36-45): closesUpcastingIntegrationEventConsumer<TEvent>for an upcasted subscription andIntegrationEventConsumer<TEvent>otherwise (:40-42) over the subscription's event type.Add(eventType, kind)(:47-62): resolves the event name (:49), then refuses a second registration whose event type or event name matches an existing one, throwingInvalidOperationExceptionthat names both and says to register each event once, current or retired, never both (:51-57). Otherwise it appends the subscription with its topic,BrokerNaming.Topic(applicationNamespace, eventName)(:60).
- Why it's built this way: the duplicate guard turns the pairing trap (a current and a retired consumer for one event would both run its handlers) into a start-up failure. Matching on the name as well as the type also catches two CLR types that declare the same
[EventName]. - Where it's used: constructed and invoked by
AddBrokerMessaging(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:91-97), which then registersConsumerTypeFor(subscription)scoped for every subscription (:103-106);BrokerReceivePipelinebuilds its dispatch table withConsumerTypeFor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:91-94). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Broker/BrokerTopologyTests.cs.
BrokerReceivePipeline
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Messaging.Consumers·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:27· Level 15 · class (internal sealed partial)
- What it is: the framework's one
IBrokerReceivePipeline, shared by every transport. Per delivered message it starts a Consumer span parented on the publisher's trace context, resolves the subscription from the event-name header, deserializes the body, and runs the subscription's consumer with in-process retry, each attempt in a fresh DI scope; when every retry fails it asks the transport for a second-level redelivery, and once those are spent it dead-letters the message with one Error log and onebroker.fault.count. An event older than the host's inbox horizon (Inbox:RetentionDays) is dead-lettered with one Warning before any handler runs (BrokerReceivePipeline.cs:12-20). - Depends on:
BrokerTopology,IServiceScopeFactory,MessageBusSettings, an optional transport redelivery-delay cap,TimeProvider,ILogger<T>and an optional inbox horizon (:69-76);BrokerTransportPoliciesfor the retry and redelivery schedule;BrokerConsumerBuilderfor the consumer types;IBrokerMessageConsumerto call them;IncomingBrokerMessagein,BrokerDispositionout (DeadLetter,Redeliver);BrokerHeaders,BrokerWire(JSON options,ActivitySource) andBrokerMetrics. Externals:System.Text.Json,System.Diagnostics. - Concept introduced, the transport decides how, the pipeline decides what.
[Rubric §10, Messaging & Integration Architecture]assesses whether retry, redelivery and dead-lettering are applied uniformly. Each transport only receives a message and applies the disposition this class returns; the policy (how many attempts, which delays, when to give up, what to log and count) lives here once (ADR-118).[Rubric §29, Resilience & Business Continuity]assesses whether failures are classified: a delivery no retry can fix (unknown event, undeserializable body, an event past the inbox horizon) is dead-lettered at once, while a handler failure is retried, then redelivered, then dead-lettered. The pipeline never throws for a handler or payload failure; the only exception it lets out is theOperationCanceledExceptionof the host's own token, and the transport then leaves the message unacknowledged so the broker redelivers it after the restart (:21-25).[Rubric §13, Observability & Operability]applies to the span and the single dead-letter Error row. - Concept, the inbox horizon.
[Rubric §8, Data Architecture]assesses whether retention and correctness agree. The inbox purge deletes a row once itsProcessedOnpasses the horizon, and a row is never processed before its event occurred, so an event still inside the horizon always finds the rows of any earlier delivery; one outside it may not, and running its handlers could repeat work the inbox can no longer prove was done (BrokerReceivePipeline.cs:38-43,:297-304). Dead-lettering it keeps ADR-021's dedup guarantee honest at the edge of retention. - Walkthrough
- Constants (
BrokerReceivePipeline.cs:29-46): the dead-letter reasons"unknown-event","poison","handler-failed"and"past-inbox-horizon", andMaxDetailLength = 1024, because brokers cap the description they store. - Constructor (
:69-95): guards its reference arguments (:78-82), builds the redelivery intervals withBrokerTransportPolicies.BuildRedeliveryIntervals(settings, maxRedeliveryDelay)(:87), keeps the inbox horizon (:90), and precomputes the dispatch table, event name to closed consumer type, withBrokerConsumerBuilder.ConsumerTypeForunder ordinal comparison (:91-94). ProcessAsync(message, cancellationToken)(:98-130): starts the span (:102), rejects throughTryResolve(:104-108), tagsmmca.event.name(:110), dead-letters an event past the inbox horizon with a Warning and a detail naming the age and the horizon (:112-119), runsConsumeWithRetryAsync(:121), returnsBrokerDisposition.Completeon success (:125), otherwiseAfterRetriesExhausted(:129).TryResolve(:136-175): a missing event name or one with no subscription is dead-lettered asunknown-eventwith a Warning (:145-152); aJsonExceptionorNotSupportedExceptionfrom deserializing withBrokerWire.JsonOptions(:157) is dead-lettered aspoisonwith the truncated message (:159-164), as is a body that deserializes to null (:166-171).IsPastInboxHorizon(:305-315): false when the host has no horizon or the event carries noDateOccurredstamp, since such an event has no provable age (:308-311); otherwise the age is the clock's UTC now minusDateOccurred(:313), and it is past the horizon when strictly greater (:314).ConsumeWithRetryAsync(:209-249): up toRetryLimit + 1attempts (:215,:218), waitingBrokerTransportPolicies.RetryDelay(settings, attempt)on the injected clock before each retry (:222-226). The catch filter (:236) lets a cancellation of the host's own token propagate and retries anything else, a handler's own timeout included (:238-239); each failed non-final attempt logs a Warning (:241-244). It returns null on success or the last exception.ConsumeOnceAsync(:251-263): creates a fresh async scope (:257), resolves the consumer asIBrokerMessageConsumer(:260) and calls it, so the inbox, origin restore and handlers of one attempt never see another attempt's tracked state.AfterRetriesExhausted(:181-202): while redeliveries remain it logs a Warning and returnsRedeliver(delay, redeliveryCount + 1)(:187-192); otherwise it logs one Error with every exception message in the chain (Describe,:318-327), adds one toBrokerMetrics.FaultCountertagged withevent_typeandqueue(:196-199), and returnsDeadLetter("handler-failed", detail)(:201).StartConsumerActivity(:270-295): parsestraceparent/tracestatefrom the headers into a remote parent (:272-280), so the publisher's sampling decision travels with the message, and starts a"{queue} process"Consumer span with the OpenTelemetry messaging tags (:282-292).- Six source-generated log methods (
:332-348).
- Constants (
- Why it's built this way: each attempt runs in a fresh scope so a failed attempt's tracked state (a staged inbox row, a dirty unit of work) cannot leak into the next one, and the second-level wait is a transport redelivery rather than an in-process delay, so a long backoff does not hold the receive call open. The horizon check runs before the first attempt, so an over-age event never reaches a handler at all.
- Where it's used: registered as the singleton
IBrokerReceivePipelinebyAddBrokerMessaging(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Messaging.cs:117-124), with the selected transport'sMaxRedeliveryDelay(:108),TimeProvider.Systemwhen no clock is registered (:122), and the horizon computed byInboxPosturefrom the boundInboxSettings, read from configuration so a host that wires the broker withoutAddInfrastructurestill honours it (:110-116). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Consumers/BrokerReceivePipelineTests.csandMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/DependencyInjectionBrokerMessagingTests.cs. - Caveats / not-in-source: the default
RetryLimit, the delay curve and the redelivery intervals are defined inMessageBusSettingsandBrokerTransportPolicies, and the horizon's value inInboxPosture, not read here; which transport receivers callProcessAsyncwas not re-read for this section.
NullFileStorageService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Storage·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Storage/NullFileStorageService.cs:14· Level 4 · class (public sealed)
- What it is: the unconfigured default for
IFileStorageService. Uploads fail with a clear, stable error; deletes succeed, because there is nothing stored to delete (NullFileStorageService.cs:6-14). - Depends on:
IFileStorageServiceas the contract andResult/Errorfor its returns. - Concept: the null-object default introduced at
NullNativePushSender, with one instructive difference.[Rubric §29, Resilience and Business Continuity]assesses whether a missing capability degrades predictably. This null object is not uniformly silent: the two operations are treated asymmetrically because their meanings differ. A caller that wanted to store something and got nothing must be told (an upload that silently succeeded while storing nothing would leave a dangling URL in the database), whereas a caller that wanted something gone already has what it asked for. - Walkthrough
IsConfiguredreturnsfalse(NullFileStorageService.cs:17), the flag the interface offers so a handler can gate a feature (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/IFileStorageService.cs:17-18).UploadAsync(blobName, content, contentType, ct)and theFileUploadOptionsoverloadUploadAsync(blobName, content, contentType, options, ct)(NullFileStorageService.cs:20-21,:25-26) both simply returnNotConfigured(): the extra options parameter changes nothing about a store that never stores anything. The options overload carries the same grandfatheredRS0026suppression as its Azure sibling (:24), since changing a shipped public signature would be a breaking change.DeleteAsync(NullFileStorageService.cs:29-30) returns success.NotConfigured()(NullFileStorageService.cs:32-36) is the private helper both upload overloads share: a failedResultcarryingError.Unexpectedwith codeFileStorage.NotConfigured, a message naming the actual condition ("No file storage is configured for this host"), andsourceset to the type name.Error.Unexpectedis the factory reserved for a genuine server-side fault the caller cannot fix and a retry will not cure, a misconfigured host among them (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Error.cs:128-141), which is exactly what a missing storage adapter is. Factoring it out is what let the second overload's implementation be a one-line forward whenFileUploadOptionswas added to the interface.
- Why it's built this way: the class doc says it directly (
NullFileStorageService.cs:7-8), feature endpoints degrade cleanly. Because the failure is aResultand not an exception (ADR-013), an avatar upload in a host with no storage configured returns a structured error with the stableFileStorage.NotConfiguredcode rather than an unhandled exception, and the same code path works whether or not the deployment has provisioned a storage account (ADR-045). Over HTTP that error surfaces as a 500, sinceErrorHttpMappingmapsErrorType.UnexpectedtoStatus500InternalServerError(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:32): the operator is meant to see a host fault, not a client mistake. - Where it's used: registered by
AddInfrastructurethroughTryAddTransient(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:433), replaced byAzureBlobFileStorageServicewhenAddAzureBlobFileStoragefinds a completeFileStoragesection (MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:44-71); the class doc names the other two adapters that swap it out,AddS3FileStorage(S3FileStorageService) andAddGoogleCloudStorage(GcsFileStorageService) (NullFileStorageService.cs:8-12).CloudAdapterTripwiredeliberately has no file-storage check and relies on this class instead: a host that lost its adapter call fails every upload withFileStorage.NotConfigured(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwire.cs:24-28). It is also the storage the ADC profile E2E suite runs against (MMCA.ADC/Tests/E2E/MMCA.ADC.E2E.Tests/Workflows/Identity/ProfileManagementTests.cs), and both upload overloads are exercised byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Storage/FileUploadOptionsOverloadTests.cs. - Caveats / not-in-source: nothing inside MMCA.Common reads
IsConfigured; the two declarations are the ones in this unit (NullFileStorageService.cs:17andAzureBlobFileStorageService.cs:26). The flag is exercised downstream: MMCA.ADC'sUploadSessionAssetHandlerchecks it before touching storage and returns its ownSessionAsset.StorageNotConfiguredfailure, whose message steers the user to add a link instead (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/UploadFile/UploadSessionAssetHandler.cs:56-62). The avatar path still discovers the unconfigured state from the failed upload result.
DeleteUserPushInstallationsInternalCommand
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.DeleteUser·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserPushInstallationsInternalCommand.cs:18· Level 4 · record (public sealed)
- What it is: the durable instruction to delete every native-push installation an erased account owns, so a device still signed in elsewhere stops receiving pushes addressed to it (
DeleteUserPushInstallationsInternalCommand.cs:5-8). Its whole payload isUserId(:18). - Depends on:
IInternalCommandas its contract andInternalCommandNameAttribute, which pins the stable queue name"MMCA.Users.DeletePushInstallations.v1"(DeleteUserPushInstallationsInternalCommand.cs:17); theUserIdentifierTypealias. - Concept: the internal command introduced at
IInternalCommand(ADR-114), used here for the part of an erasure that lives outside the database.[Rubric §30, Compliance, Privacy & Data Governance]assesses whether erasure reaches every copy of personal data. A push installation is held by the push provider (ADR-044), outside the unit of work, so it cannot be anonymized in the same save; scheduling this command inside the erasure's unit of work makes the instruction commit with the anonymized account or roll back with it, and the processor retries it until the provider answers (DeleteUserPushInstallationsInternalCommand.cs:9-14). - Walkthrough: a positional record with one property; the remarks note that the user id alone round-trips through JSON, as the queue requires (
:14). - Where it's used: scheduled by
DeleteUserHandlerBase<TUser, TCommand>when the subclass forwards anIInternalCommandScheduler(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:195-204); run byDeleteUserPushInstallationsInternalCommandHandler.
DeleteUserPushInstallationsInternalCommandHandler
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.DeleteUser·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserPushInstallationsInternalCommandHandler.cs:21· Level 5 · class (internal sealed partial)
- What it is: the handler that runs
DeleteUserPushInstallationsInternalCommandby deleting the erased account's installations through the host'sIPushDeviceRegistrar(DeleteUserPushInstallationsInternalCommandHandler.cs:7-10). - Depends on:
IPushDeviceRegistrarandILogger<T>as primary-constructor parameters (:21-23); implementsICommandHandler<in TCommand, TResult>overResult(:24). - Concept: at-least-once execution demands idempotency. The remarks spell out the contract (
DeleteUserPushInstallationsInternalCommandHandler.cs:12-17): installations already deleted are simply no longer found, so a rerun is harmless; a failure is returned unchanged so the row stays on the processor's backoff, because a push provider outage is exactly what the durable queue exists to survive. - Walkthrough
HandleAsync(command, cancellationToken)(:27-42): guards the command (:29), callsregistrar.DeleteAllForUserAsync(command.UserId, ...)(:31), logs one line per outcome (:32-39), and returns the registrar's result as-is (:41).LogInstallationsDeletedat Information andLogInstallationsDeleteFailedat Warning (:44-48), source-generated[LoggerMessage]methods (hencepartial), each carrying the user id only.
- Where it's used: registered by
AddApplication()withTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:75), so a host needs no registration of its own; the internal-command processor resolves it like any other command handler, so the decorator pipeline applies. Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/DeleteUser/DeleteUserPushInstallationsInternalCommandHandlerTests.cs. - Caveats / not-in-source: the command runs on the host that wrote the row. On a host with no push adapter the registrar is the inert
NullPushDeviceRegistrarand the command completes having deleted nothing (:15-17), so the host that schedules it must be the one that registers the adapter.
ChangePreferencesCommandValidatorBase<TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ChangePreferences·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommandValidatorBase.cs:29· Level 6 · class (abstract)
What it is: the shared FluentValidation rules for a change-preferences command: the request must be present, a supplied culture must be one the framework supports, and a supplied theme must be light or dark. A
nullfield passes, becausenullis the documented "leave this preference unchanged" value (ChangePreferencesCommandValidatorBase.cs:8-13,:30-70).Depends on: FluentValidation's
AbstractValidator<TCommand>(:1,:30);TCommandis constrained toIUserScopedCommand<out TRequest>carrying aChangePreferencesRequest(:31). The accepted values come fromSupportedCultures.IsSupported(:51,MMCA.Common/Source/Core/MMCA.Common.Shared/Globalization/SupportedCultures.cs:35) andCommonInvariants(LightTheme/DarkThemein the message at:58,EnsurePreferredThemeIsValidat:67-69;MMCA.Common/Source/Core/MMCA.Common.Domain/Invariants/CommonInvariants.cs:16,:19,:158).Concept introduced: a command validator that borrows the aggregate's own definition of valid.
[Rubric §24: Forms, Validation & UX Safety]assesses whether bad input is rejected early, with a stable, client-readable reason. Each rule carries a fixed message and error code (User.Preferences.Required,User.PreferredCulture.Invalid,User.PreferredTheme.Invalid,:33-40), so a bad culture or theme is turned away before the handler runs instead of surfacing as an aggregate failure after a load.[Rubric §4: DDD]assesses whether invariants have one home. The validator does not restate the theme rule:BeAKnownThemecallsCommonInvariants.EnsurePreferredThemeIsValidand keeps only itsIsSuccess(:64-69), and the culture rule uses the sameSupportedCultures.IsSupportedallowlist, so moving the rejection forward adds no second definition of what is valid (remarks at:22-27). Culture and theme are the ADR-027 and ADR-028 preferences (ADR-027, ADR-028;:9).Walkthrough: three private error-code constants, a protected constructor, one private helper.
PreferencesRequiredCode,CultureInvalidCode,ThemeInvalidCode(:34,:37,:40).- Constructor (
:43-62):RuleFor(c => c.Request).NotNull()(:45-46); then, only when the request is present (When,:48), a culture rule gated onCulture is not null(:50-54) and a theme rule gated onTheme is not null(:56-60). The outerWhenis what keeps a missing request down to the single "required" failure rather than a cascade of null dereferences. BeAKnownTheme(string?)(:67-69): delegates to the domain invariant with an empty message and reads only the outcome.
Why it's built this way: it is a COMMAND validator rather than a request validator on purpose. The command carries its payload through
IUserScopedCommand<out TRequest>, which does not opt it into the automaticCommandRequestValidator<TCommand, TRequest>bridge, so anIValidator<ChangePreferencesRequest>would never run (:16-19). It is abstract because module scanning registers validators from the app assemblies only: each app declares a one-line sealed subclass for its own command record, the same split asChangePreferencesHandlerBase<TUser, TCommand>(:19-21). The remarks record that the app Identity modules carried near-identical copies before this base existed (:12-13).Where it's used: ADC's
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommandValidator.cs:10is the one-line sealed subclass overChangePreferencesCommand. Pinned byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/ChangePreferences/ChangePreferencesCommandValidatorBaseTests.cs:18through an empty test subclass (:163): a null request yields only the required failure (:33), null fields pass (:48), every culture inSupportedCultures.Allpasses (:57), and two parity theories assert the validator agrees withCommonInvariants.EnsurePreferredThemeIsValidandEnsurePreferredCultureIsValidon edge inputs such as"DARK"," light","es-MX"and""(:102,:122).
DeleteUserHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.DeleteUser·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:95· Level 8 · class (abstract)
What it is: the shared account-erasure workflow: authorize owner-or-privileged-role, soft-delete the account, run the app's tail hook, irreversibly anonymize the personal data in place, revoke and anonymize the account's refresh-session rows, blank its email on the support access log, schedule the deletion of its native-push installations, save, write the shared soft-deleted marker that revokes the account's already-issued access tokens, then drain a post-save queue (
DeleteUserHandlerBase.cs:14-26,:117-222). It exposes one abstract member and one virtual hook.Depends on: six required parameters and one optional one (
:95-102):IUnitOfWork, anISoftDeletedUserMarkerWriter, anILogger, anIRefreshSessionStore, anIViewAsGrantStoreand anIInternalCommandScheduler, then aTimeProviderthat defaults to null (the system clock). The three erasure-step dependencies are required on purpose: the session and grant stores are registered byAddInfrastructureon every host and are inert when their feature is off, so "a subclass cannot skip it by forgetting to forward the store" (:72-84, and:85-93for the scheduler). ImplementsICommandHandler<in TCommand, TResult>overResult(:102). The session helper is the sharedRefreshSessionRevocation(:176-178). Constraints:TUseris anAuditableAggregateRootEntity<TIdentifierType>implementingIErasableUser(:103), andTCommandis anIUserOwnedRequest(:104), not anIUserScopedCommand<out TRequest>: this workflow needs the caller as well as the target, and carries no request payload. It also usesUserOwnershipRule,ErrorandDeleteUserPushInstallationsInternalCommand, and logs through two private source-generated[LoggerMessage]methods,UserErasedat Information (:255-256) andSoftDeletedMarkerFailedat Warning (:258-259), hence thepartialdeclaration (:95). Externals:Microsoft.Extensions.Logging(:1).Concept introduced: anonymize-in-place erasure, and why the row survives. Soft-delete (
IsDeleted = true) hides a row but keeps its personal data, so it does not by itself satisfy a GDPR/CCPA erasure request; hard-deleting the row would break cross-context scalar references and destroy the audit trail. The framework's answer is the pairIAnonymizableplusIErasableUser: keep the row, overwrite the personal fields with non-identifying placeholders, and requireAnonymize()to be idempotent (MMCA.Common/Source/Core/MMCA.Common.Domain/Interfaces/IAnonymizable.cs:24-30). This handler is where that policy becomes a sequence (ADR-005).Concept introduced: interface dispatch as a correctness device. The comment at
:147-149states the rule briefly: the base callsDelete()through anIErasableUserlocal (:150-151), so interface dispatch runs theDelete()the app type maps ontoIErasableUser, and aUserthat forgets the interface fails theTUserconstraint at compile time. The reason it matters: an app'sUsermay hide the base entity'sDelete()withpublic new Result Delete(). A hidden method is not an override, and member lookup on a generic type parameter prefers the members of its class constraint, so a bareuser.Delete()here would bind toAuditableBaseEntity<TIdentifierType>.Delete()and silently skip the app's version. The interface's own remarks record the same reasoning from the contract side (IErasableUser.cs:13-23), including the deliberate choice not to implement it on the base entity (IErasableUser.cs:18-19).Concept introduced: the post-save queue.
OnAfterSoftDeleteAsyncreceives anICollection<Func<CancellationToken, Task>> afterCommit(:248-253). Work that must not happen unless the erasure is actually saved (deleting a blob, notifying another system) is enqueued rather than run inline, and the base drains the queue in order after the save and the marker write (:214-217). The override can hand values it captured before anonymization to a post-save closure without parking them in mutable handler state (:53-55), which matters because a scoped handler's field would be shared mutable state for the whole request. The class summary is precise about what "after" means: under anITransactionalcommand the save is not the commit, so the marker and everyafterCommitaction run before the transaction commits, and only idempotent, retry-safe work belongs there; anything that must survive with the erasure should be scheduled as an internal command inside the unit instead (:22-25, repeated on the parameter at:238-245).Concept introduced: token revocation as part of the shared workflow, best effort and first. Between the save and the queued actions the base writes the shared soft-deleted marker through
markerWriter.MarkDeletedAsync(:207), which is what stops an erased account's already-issued access token from working before the next database lookup would notice; the API middleware readsSoftDeletedUserCacheon every host, and on a host without the soft-deleted-user validator query the marker is the only thing that rejects such a token (:29-32, ADR-047). The writer sizes the marker to outlive every access token issued before the erasure, andAddApplicationregisters it (:67-70). Two decisions are documented on the class and are worth reading as a pair. It is best effort (:33-37): the erasure is already saved, so a cache fault must not turn a successful, irreversible deletion into a failure the caller would retry, and the write is wrapped in atry/catch(excludingOperationCanceledException) that logsSoftDeletedMarkerFailedand continues (:205-212). The warning text states the consequence: the Identity host still rejects the deleted user's access token, but a host without the account-status query accepts it until it expires (:258-259). And it runs before the queued actions (:40-43), because that tail is unbounded app work and every second it takes is a second the deleted account's token still works. Owning the marker here rather than in each app's tail gives both apps the identical revocation window; the hook's own docs tell an override not to queue a marker write (:243-244).Concept introduced: personal data held beside the account is erased in the same unit. Three unconditional steps run after the user's own
Anonymize()and before the save. None of them is guarded by a null check, because every dependency they use is a required constructor parameter (:99-101); on a host where refresh sessions or view-as are switched off, the registered store is inert rather than absent (:73-74,:80-81):- Refresh sessions (
:171-178): a session stores the IP address and user agent captured at sign-in, on revoked rows as much as live ones.RefreshSessionRevocation.RevokeAndAnonymizeAllAsyncrevokes every un-revoked session and anonymizes every row; the store hands back tracked rows on the same context factory, so the changes commit or roll back with the erasure in the one save (:199). - The support access log (
:180-184):viewAsGrants.ForgetUserAsyncblanks the account's email snapshot on every view-as grant naming it, as staff or as the viewed account; the grant rows themselves stay untilViewAs:RetentionDayssweeps them (ADR-137). - Native-push installations (
:186-197): these live with the push provider, outside the unit of work, so the base schedules aDeleteUserPushInstallationsInternalCommandthrough the scheduler instead of calling the provider inline. The row commits with the erasure and the processor retries it until the provider answers (ADR-044, ADR-114). A scheduling failure fails the erasure (:194-197), because a partial erasure reported as a success is worse than a retryable failure (:189-190). The command runs on the host that wrote the row, so that host must register the push adapter; with the inert default registrar it completes having deleted nothing (:90-91).
[Rubric §30: Compliance, Privacy & Data Governance]assesses whether a data-subject erasure request is actually satisfiable. The sequence here is the mechanism behind both apps' published erasure promise: soft-delete, then irreversible anonymization of the account and the rows beside it, persisted in one save (:14-21).[Rubric §11: Security]assesses authorization placement. The very first thing the method does, before it touches the repository, is the ownership check (:123-133), so an unauthorized caller cannot even confirm that an account id exists. The privileged-role test is passed in already evaluated because each app owns its own role vocabulary (UserOwnershipRule.cs:14-18).[Rubric §1: SOLID]assesses the template-method shape. The invariant order (authorize, load, delete, tail, anonymize, session revoke-and-anonymize, view-as forget, push-deletion schedule, save, token revoke, queued actions) is fixed by the base; only the two hooks vary, and no subclass can drop an erasure step by leaving out a constructor argument (:76-77).- Refresh sessions (
Walkthrough: two protected members, the handler method, two hooks and two log methods.
- Primary constructor (
:95-102): the requiredunitOfWork,markerWriter,logger,refreshSessions,viewAsGrantsandinternalCommandScheduler, then the optionaltimeProviderlast (:102).UnitOfWork(:107) is protected specifically so a tail hook can enlist further aggregates. HandlerName(:114):GetType().Nameby default, so an app subclass namedDeleteUserHandlerreports that name as the errorsource(:109-113).HandleAsync(TCommand, CancellationToken)(:117-222):- Authorization first (
:124-129) throughUserOwnershipRule.CheckOwnership(UserOwnershipRule.cs:37), with the code"User.DeleteForbidden"and a message the caller sees; a non-null return is the failure (:130-133). - Load through the write repository (
:135-136);Error.NotFoundwhen absent (:139). IErasableUser erasable = user; erasable.Delete()(:150-151) with the dispatch rationale above; a failure returns immediately (:152-155). The comment there points forward to the session handling: refresh sessions are revoked and anonymized further down, not left to the app (:144-145).- Allocate the
afterCommitlist and callOnAfterSoftDeleteAsync(:157-158); a failed tail aborts before anything is persisted (:159-162). erasable.Anonymize()(:165), also short-circuiting on failure (:166-169).RefreshSessionRevocation.RevokeAndAnonymizeAllAsync(refreshSessions, timeProvider, ...)(:176-178), thenviewAsGrants.ForgetUserAsync(:184), then the push-deletion schedule (:191-197), all three unconditional.SaveChangesAsync(:199), then the best-effort marker write (:205-212), then the queued actions drained in order (:214-217), then theUserErasedlog (:219) andResult.Success()(:221).
- Authorization first (
HasDeletePrivilege(string? currentUserRole)(:230):protected abstract. Deliberately abstract rather than virtual-defaulting-to-false, so adopting the base forces an explicit answer about which role bypasses ownership; its XML doc namesUserRole.IsAdmin(...)only as an example of "whatever the app's privileged role is" (:224-229).OnAfterSoftDeleteAsync(user, command, afterCommit, cancellationToken)(:248-253):protected virtual, defaulting toTask.FromResult(Result.Success()); returning a failure aborts the erasure before anything is persisted (:233-234). Its position is load-bearing and documented: it runs afterDelete()and beforeAnonymize()(:49-52), which is the only point where an override can both read personal data that anonymization is about to erase and enlist further aggregates in the same unit of work. Running it afterDelete()rather than before means an already-deleted account fails with its ownAlreadyDeletederror rather than one raised by a cascaded aggregate (:59-61).
- Primary constructor (
Why it's built this way: the hook contract was derived from what the two apps actually needed, and both uses are visible in their overrides. ADC's override (
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserHandler.cs:55-86) captures the avatar blob name before anonymization clears the URL (DeleteUserHandler.cs:63), raises the cross-serviceUserDeletedevent on the aggregate so its outbox row is written by the very save that commits the erasure (:71), and schedules the avatar blob deletion as a durable internal command throughIInternalCommandSchedulerinside the erasure transaction rather than queueing it onafterCommit, so an erasure that persists can never lose the instruction to delete the photo (:73-83,:88onward). Store instead cascades in the same unit of work, erasing the linkedCustomerthat holds its name/email/address PII and returning the Customer's own failure untouched so nothing is persisted (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/DeleteUser/DeleteUserHandler.cs:56-60,:62onward). One hook covers both because it can do work inline and schedule work for after the save.Where it's used: subclassed once per app, each supplying its own privileged role to
HasDeletePrivilegeand forwarding every required dependency. ADC (MMCA.ADC/.../DeleteUser/DeleteUserHandler.cs:37-45) forwards the marker writer, the refresh-session store, the view-as grant store and its scheduler, and does not pass a clock to the base (it injects its ownTimeProviderto stamp theUserDeletedevent,:41,:71), withHasDeletePrivilegereturningUserRole.IsOrganizer(...)(:51-52); its remarks state that the two stores are required because the base requires them (:33-35). Store (MMCA.Store/.../DeleteUser/DeleteUserHandler.cs:41-48) forwards the same four, the view-as grant store included, withUserRole.IsAdmin(...)(:51-52); its own doc notes Store registers no push adapter, so the push command completes having deleted nothing there (:36-39).AddApplication()registers the push command's handler (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:75). Covered directly byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/DeleteUserHandlerBaseTests.cs, whose fixture user type isTestHidingDeleteUser(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UserUseCaseTestDoubles.cs) precisely so the hidden-Delete()dispatch rule above is a regression test rather than a comment.Caveats: queued
afterCommitactions run after the erasure has been saved, so each one owns its own failure handling; the base does not wrap them (:214-217, and see the documented expectation at:238-245). Under anITransactionalcommand they, and the marker, run before the commit (:22-25). The one exception to "not wrapped" is the marker write the base performs itself, which it does wrap (:205-212). The class summary still words the session and grant steps conditionally ("when the host registered a session store", "when the subclass forwards the grant store",:16-18); the parameter docs (:72-84) and the code (:176-184) are the current contract, and both steps always run. Both apps'DeleteUserCommandrecords areICacheInvalidating, so the cache prefix they carry is invalidated by the decorator after the handler returns success, outside this class.
ForgotPasswordHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ForgotPassword·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:63· Level 8 · class (abstract)
What it is: the shared start-a-password-reset workflow, split across two executions of the same command. The inline dispatch (the anonymous endpoint) only schedules the command as an internal command and answers
Result.Success(); the scheduled execution parses the address, resolves the account behind it, mints a single-use token and emails it (ForgotPasswordHandlerBase.cs:19-23,:63,:80-89). The email is composed in the recipient's culture (:133-135).Depends on:
IUnitOfWork,IPasswordResetTokenService,IEmailSender,IInternalCommandScheduler,IOptions<PasswordResetSettings>and anILogger(:63-69); implementsICommandHandler<in TCommand, TResult>overResult(:69). Constraints:TUseris anAuditableAggregateRootEntity<TIdentifierType>keyed byUserIdentifierTypethat also implementsIEmailIdentifiedUser(:70), the one capability the workflow needs: that interface exposes the account'sEmail(MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IEmailIdentifiedUser.cs:18-21), and the framework's internalUserEmailLookup.FindUntrackedByEmailAsyncextension finds the account through it (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:38-43). Beyond that the workflow reads onlyId(:124) and hands the account toUserEmailResources.InRecipientCultureto pick the email culture (:133-135);TCommandis anICommandWithRequest<out TRequest>carrying aForgotPasswordRequestand also anIInternalCommand(:71), so the app gives it anInternalCommandNameAttribute(:53-56). It also uses theEmailvalue object (:107), readsInternalCommandExecution.IsActiveto pick the path (:86), and logs through three private source-generated[LoggerMessage]methods (:191-200), hence thepartialdeclaration (:63). Externals:System.Globalization,System.Net.WebUtility,Microsoft.Extensions.LoggingandMicrosoft.Extensions.Options(:1-4).Concept introduced: anti-enumeration by never looking the address up inline. A response that differs between "we sent you a reset link" and "no such account" is an account-enumeration oracle: anyone can walk an address list and learn which addresses are registered. The inline dispatch therefore does no lookup at all. It writes one queue row and answers success (
:92-102), so neither the response nor its timing depends on whether the address is registered (class remarks:26-30). Only two things make it answer anything else: the request validator, which inspects the shape of the address alone (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ForgotPasswordRequestValidator.cs:11-16), and a failure to write the queue row, an infrastructure fault that does not depend on the address and is returned asResult.Failure(scheduled.Errors)after an Error-levelPasswordResetScheduleFailedline (:95-99,:194-195).[Rubric §11: Security]assesses whether a public endpoint leaks facts about who holds an account. On the scheduled execution, the three ways to send nothing all complete the row withResult.Success()and differ only in a log reason: a malformed address (:107-112), an address with no account (:114-122) and a request the token service throttled (:124-129). EachResultcheck reads its value throughTryGetValue(out ...)rather than anIsFailuretest followed by a null-forgiving.Value!(:108,:125). The controller turns the inline success into a202 Accepted(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:82-93). The rejection log,PasswordResetRejected, carries a reason string but no address and no account id, so the log does not become the oracle the response is not (:197-200, the comment at:197-198says so). OnlyPasswordResetRequested(:191-192), reached after an account resolved and the mail went out, logs a user id;PasswordResetScheduleFailedlogs nothing about the request (:194-195).[Rubric §29: Resilience & Business Continuity]assesses what happens when a dependency fails mid-workflow. On the scheduled execution a send failure propagates rather than being caught (:131-136): there is no caller to leak it to, so the processor logs it with the stack and retries the row with backoff, a retry issues a fresh token that replaces the undelivered one, and a row that never clears is dead-lettered, visibly (:36-38). A throttle refusal, by contrast, completes the row: every row comes from an anonymous request, so the refusal is the per-address limit doing its job, not work to retry (:33-36). The token is issued in the scheduled execution rather than inline because nothing needs it before the response, and carrying it in the queue row would store the raw credential the token service keeps out of the database (:38-40).[Rubric §3: Clean Architecture]assesses dependency direction. The workflow lives in the Application layer and reaches the SMTP relay, the token cache, the queue and the database only through interfaces. Even the address-to-account lookup over an app-ownedUseraggregate is framework code: an EF-translated predicate onIEmailIdentifiedUser.Email(UserEmailLookup.cs:28-30), so the base declares no abstract member and the app supplies only the command record and, optionally, the email wording (:43-46).Walkthrough: two protected properties, the handler method, two private paths, three hooks and three log methods.
- Primary constructor (
:63-69):unitOfWork,tokenService,emailSender,scheduler,settings,logger. UnitOfWork(:74): exposed for app-level extensions (:73).Settings(:77):settings.Value, unwrapped once so the body readsSettings.TokenLifetimeMinutesrather thansettings.Value....HandleAsync(TCommand, CancellationToken)(:80-89): null-guard (:84), thenInternalCommandExecution.IsActivepicksSendAsyncon the scheduled execution andScheduleAsyncon the inline dispatch (:86-88).ScheduleAsync(:92-102): private.scheduler.ScheduleAsync(command, ...)(:94); a failure logsPasswordResetScheduleFailedand returns the failure (:95-99), otherwise success (:101).SendAsync(:105-140): private.Email.Createon the raw string, unwrapped withTryGetValue, so a malformed address never reaches the lookup (:107-112); the untracked lookup throughGetReadRepository<TUser, UserIdentifierType>().FindUntrackedByEmailAsync(...), theUserEmailLookupextension (:114-117);tokenService.IssueAsync(email.Value, user.Id, ...)(:124), whose failure (aTryGetValuemiss at:125) means the per-email throttle fired; then oneUserEmailResources.InRecipientCulture(user, ...)call that runsComposeSubject()andComposeBody(ComposeResetLink(...), token)under the account's stored culture and returns the(subject, body)pair (:133-135), sent as HTML with no surroundingtry(:136); and finally thePasswordResetRequestedlog and success (:138-139).ComposeSubject()(:148):protected virtual,UserEmailResources.Get("ForgotPassword.Subject"). It runs with the current UI culture set to the account's stored preference (the request's culture when the account has none), so the default is localized and an override is only needed to rebrand (:142-148).ComposeBody(string? resetLink, string token)(:158-169):protected virtual. It carries the link and the raw token, because clients without deep linking (the MAUI head) need the token typed into the reset page by hand (:151-153). Every visible string (link text, intro, the code-with-expiry line, the ignore notice) is aUserEmailResourceslookup, the code line throughUserEmailResources.Pluralkeyed onSettings.TokenLifetimeMinutes(:163-168). Both the link and the token go throughWebUtility.HtmlEncodebefore interpolation into the HTML (:163,:167), and the expiry is rendered withCultureInfo.InvariantCulture(:160).ComposeResetLink(string email, string token)(:186-189):protected virtual. ReturnsnullwhenPasswordResetSettings.ResetUrlis blank, so an unconfigured host degrades to a token-only email rather than emailing a broken link; otherwise it appends#email=...&token=...with both valuesUri.EscapeDataString-encoded, as a URL fragment rather than a query string.PasswordResetRequested(Information),PasswordResetScheduleFailed(Error) andPasswordResetRejected(Information) (:191-200):private static partial, the three source-generated audit lines described under Security.
Concept introduced: the live token rides in the URL fragment, not the query string. A fragment is never sent to a server, so putting the address and the single-use token there keeps them out of ingress access logs, out of request telemetry (
url.queryis exported unredacted), and out of anyRefererheader the reset page emits; the page itself reads the values fromlocation.hashand scrubs them from the address bar (:179-185, remarks onComposeResetLink).- Primary constructor (
Why it's built this way: the reset token is deliberately not a database row. It lives in the distributed cache, hashed at rest, with the per-email request throttle and the per-token attempt cap enforced by the token service rather than by this handler (ADR-091;
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:59-60,:74,:169). That split is why the scheduled execution's only reaction to a throttled request is a log line: it never learns which limit fired. Running the lookup and send as an internal command (ADR-114) means a mail outage defers the email instead of losing it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordCommand.cs:12-17). The command record stays app-side, matching the ChangePassword hoist, and the base reads it only throughICommandWithRequest<ForgotPasswordRequest>(:43-44).Where it's used: subclassed once per app (
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandler.cs:21;MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandler.cs:24). Neither app subclass has a body: each only binds the base to its ownUseraggregate and command through a primary constructor (ADCMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandler.cs:28, StoreMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandler.cs:31), so the untracked account-by-address lookup runs in the base for both apps. ADC's command carries[InternalCommandName("Identity.ForgotPassword.v1")](ForgotPasswordCommand.cs:19-21). Reached over HTTP throughPasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>, whosePOST forgot-passwordaction is[AllowAnonymous], rate-limited by the auth-IP policy and[Idempotent](PasswordResetAuthControllerBase.cs:75-93). Pinned byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/ForgotPasswordHandlerBaseTests.cs:24through a test subclass (:322): the scheduled-path rejections, send, fragment and unconfigured-ResetUrlcases (:31,:46,:61,:83,:100,:113), a throwing send that propagates so the row retries (:129), the inline dispatch scheduling without lookup, issue or email whether or not the account exists (:154), a schedule failure returned (:172), and the recipient culture (:189,:210).Caveats: the anonymous command carries no user identifier, which is why it implements
ICommandWithRequest<out TRequest>rather thanIUserScopedCommand<out TRequest>(ForgotPasswordCommand.cs:20-21). The base never callsSaveChangesAsyncitself: the queue row is written byIInternalCommandScheduler, and the unit of work is present only for the untracked account read (:114-116).
ResetPasswordHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ResetPassword·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:42· Level 8 · class (abstract)
What it is: the shared complete-a-password-reset workflow: redeem the single-use token, revoke every live refresh session on the account, hash the new password, let the aggregate apply its invariants, persist, then clear the account's lockout so the user can sign in immediately with the new credential (
ResetPasswordHandlerBase.cs:42,:66-124).Depends on:
IUnitOfWork,IPasswordHasher,IPasswordResetTokenService,ILoginProtectionServiceand anILogger, plus a requiredIRefreshSessionStoreand an optionalTimeProvider(:42-49); implementsICommandHandler<in TCommand, TResult>overResult(:49). Constraints:TUseris anAuditableAggregateRootEntity<TIdentifierType>implementingIPasswordChangeableUser(:50), the same capabilityChangePasswordHandlerBase<TUser, TCommand>requires, andTCommandis anICommandWithRequest<out TRequest>carrying aResetPasswordRequest(:51). Also usesError, and logs through two private source-generated[LoggerMessage]methods,PasswordResetCompleted(:132-133) andPasswordResetRejected(:137-138), hence thepartialdeclaration (:42). Externals:Microsoft.Extensions.Logging.Concept introduced: burn the token before the write, not after. The token is consumed at the top of the method, before anything is saved (
:77-79), and the comment explains the trade: leaving it live until the write succeeds opens a replay window in which the same token redeems twice, while burning it early costs a user whose aggregate then rejects the change one extra reset request (:74-76). Choosing the second cost is the security-over-convenience call, and it is pinned by its own test,HandleAsync_ConsumesTheTokenBeforeSaving(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/ResetPasswordHandlerBaseTests.cs:113).Concept introduced: one error for every rejection. Unlike the authenticated change-password path, which can afford a specific
Auth.InvalidCurrentPassword, this anonymous endpoint collapses an unknown token, an expired token, a mismatched token, an attempt-capped token and a vanished account into a singleAuth.InvalidResetToken(:126-130, produced at:83and:92). The privateInvalidToken()factory exists so there is exactly one construction site and no way for a future edit to make two branches distinguishable by accident.[Rubric §11: Security]assesses whether an anonymous endpoint leaks account state. Two mechanisms do the work here: the uniform error above, and a rejection log that names only a reason string, never an address or an account id (:82,:91, and the declaration with its comment at:135-138). The matching controller action turns every failure into the same401(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:99-118).[Rubric §29: Resilience & Business Continuity]assesses whether a user can recover unaided. The finalResetFailedAttemptsAsynccall (:120) is the part that makes a reset actually usable: a user who reset the password because the brute-force lockout locked them out would otherwise still be locked out with a brand-new credential (ADR-029;ILoginProtectionService.cs:33).Concept introduced: a reset is the remediation for a suspected intruder, so the intruder's session has to die with the old password. Once the token is redeemed and the account loaded, and before the new password is even hashed, the handler revokes every live refresh session on the account through the required
IRefreshSessionStore, using the sharedRefreshSessionRevocationhelper (:106-108, comment at:95-105), the same helperChangePasswordHandlerBase<TUser, TCommand>uses (ADR-097). The order is deliberate (the comment tags it M240): the session store saves through the shared context factory, which saves every cached context, so a user already mutated byChangePasswordwould ride along in the revoke's save. With the user still unmodified the revoke save carries only the sessions, and a failure between the two saves can never leave a new password with the old sessions alive. Revoking is always desirable on a reset, so it also stands when the aggregate then rejects the new password. A revoke failure throws before anything else changes, leaving the password and the lockout as they were, with the token already spent (the user requests a new link). Only thetimeProviderparameter defaults tonull; the base caches it in a private_timeProviderfield, falling back toTimeProvider.System(:53), and a caller must supply the refresh-session store explicitly.[Rubric §4: DDD]assesses whether the rules live in the domain. As with the change-password base, the handler hashes and then callsuser.ChangePassword(newHash, newSalt)(:110-111), returning the aggregate's own result on failure without saving or clearing the lockout (:112-115); the session revocation has already happened by then (:106-108).Walkthrough: two protected members, the handler method, one private helper and two log methods.
- Primary constructor (
:42-49):unitOfWork,passwordHasher,tokenService,loginProtection,logger, the requiredrefreshSessions, and the optionaltimeProvider. Seven collaborators, one more thanChangePasswordHandlerBase<TUser, TCommand>, because a reset touches the token store, the hasher, the database, the refresh session store and the lockout store in one pass. UnitOfWork(:56) andHandlerName(:63): the same two protected members as the other bases, with the same rationale (an app subclass namedResetPasswordHandlerreports that name as the errorsource,:58-62).HandleAsync(TCommand, CancellationToken)(:66-124): null-guard (:70); redeem the token viaValidateAndConsumeAsync(request.Email, request.Token, ...)(:77-79) and fail generically on rejection (:80-84); take the account id the token resolved to (:86) and load it through the write repository (:87-88), failing with the same generic error if it is gone (:89-93); revoke every refresh session (:106-108); hash the new password (:110) and call the aggregate (:111);SaveChangesAsync(:117); clear the lockout (:120); logPasswordResetCompletedand return the aggregate's success result (:122-123).InvalidToken()(:126-130): the singleError.Unauthorized("Auth.InvalidResetToken", ...)construction, stamped withHandlerName.PasswordResetCompletedandPasswordResetRejected(:132-138):private static partial, the source-generated audit lines.
- Primary constructor (
Why it's built this way: the reset half of the recovery vertical had to share the change-password hoist's shape (generic in the aggregate, generic in the command, one virtual
HandlerName) so that both credential-write paths report errors identically and neither app has to restate the workflow (ADR-091). The one ordering decision it owns, consuming before saving, is documented in the code rather than left to be rediscovered (:74-76). New-password strength is not re-checked here becauseResetPasswordRequestValidatorincludes the sameStrongPasswordRules<T>set the registration and change-password requests use, so a reset cannot be a way around the complexity policy (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ResetPasswordRequestValidator.cs:12-23).Where it's used: subclassed once per app as an empty, name-preserving class (
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordHandler.cs:24,:24-29;MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordHandler.cs:20,:26-31). Reached over HTTP through thePOST reset-passwordaction onPasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>(PasswordResetAuthControllerBase.cs:99-118), which answers204 No Contenton success. Pinned by five tests inMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/ResetPasswordHandlerBaseTests.cs:20through a test subclass (:176-181), covering both generic-error paths, the happy path, the aggregate rejection and the consume-before-save ordering (:28,:48,:64,:85,:111).Caveats: the command record stays app-side, and the two apps declare it with the same shape: ADC's
ResetPasswordCommandis a plainICommandWithRequest<ResetPasswordRequest>(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:10-11) and so is Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:12-13); neither implementsICacheInvalidating. The lockout clear at:120runs last, after the revocation and the save, and is not part of the transaction: if it throws, the password has already changed. It clears the counter keyed by the request's email address (request.Email,:120), which is the sign-in counter; the separatepassword-change:{userId}counter thatChangePasswordHandlerBase<TUser, TCommand>keeps is not touched here. Not determinable from source: whether any deployment configures aResetFailedAttemptsAsyncimplementation that can fail in a way the caller would notice, since the contract returns a bareTaskwith no result (ILoginProtectionService.cs:33).
ChangePasswordHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ChangePassword·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:55· Level 8 · class (abstract)
What it is: the shared password-rotation workflow for an authenticated user. Load the account, reject a credential-less account, check the per-account change-password lockout, verify the current password against the stored hash (counting a miss against the lockout), hash the new one, let the aggregate apply its own invariants, and persist only if the aggregate accepted the change (
ChangePasswordHandlerBase.cs:55,:78-136).Depends on:
IUnitOfWork,IPasswordHasherand anILoggeras primary-constructor parameters, plus a requiredIRefreshSessionStore, a requiredILoginProtectionServiceand an optionalTimeProvider(:55-61); it implementsICommandHandler<in TCommand, TResult>closed overResult(:61). Its two constraints are the interesting part:TUsermust be anAuditableAggregateRootEntity<TIdentifierType>keyed byUserIdentifierTypeand implementIPasswordChangeableUser(:62), andTCommandmust be anIUserScopedCommand<out TRequest>carrying aChangePasswordRequest(:63). It also usesError, and its audit line is a private source-generated[LoggerMessage]method,PasswordChanged(:147-148), which is why the class is declaredpartial(:55). Externals:System.GlobalizationandMicrosoft.Extensions.Logging(:1-2).Concept introduced: the generic template-method handler, and the two axes it is generic over. One workflow serves both app Identity modules (
ChangePasswordHandlerBase.cs:14-17), which needs two variation points, and each is a separate generic parameter for a separate reason.TUservaries because each app owns its ownUseraggregate and the framework must never reference either; the capability it needs is named by an interface constraint instead, so the base can callChangePasswordwithout knowing the type (IPasswordChangeableUser.cs:19).TCommandvaries because each app declares its own command record in its own Identity.Application namespace: ADC'sChangePasswordCommand(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:12-13) and Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:13) have the same shape, and neither implementsICacheInvalidating. The base reads the command only throughIUserScopedCommand<out TRequest>, which is deliberately notICommandWithRequest<out TRequest>: that marker also opts the command into automaticCommandRequestValidator<TCommand, TRequest>registration, which is a per-app decision (IUserScopedCommand.cs:6-12), and the class remarks record the same split (ChangePasswordHandlerBase.cs:19-24).[Rubric §1: SOLID]assesses open/closed and dependency inversion. The workflow is closed for modification and open for extension along exactly two declared axes plus theHandlerNamehook, and every collaborator is an abstraction: unit of work, hasher, lockout service, refresh-session store, logger, and the aggregate's own capability interface.Concept introduced: a credential-less account has no current password to prove, so it has no change-password path either. An external-OAuth account carries an empty
PasswordHashandPasswordSalt(ADR-036), and the handler rejects that case explicitly, before the lockout check and the verify, rather than letting a zero-length hash compare against anything (:91-99).Concept introduced: a wrong current password counts against a lockout, just as a failed sign-in does. Without it, anyone holding a live session could use this endpoint as an unthrottled password oracle. The handler therefore runs the current-password check through the same failed-attempt counter and exponential lockout the sign-in path uses (ADR-029):
CheckLockoutAsyncbefore the verify, returning its failure as-is when the key is locked (:101-106);IncrementFailedAttemptsAsyncon a mismatch (:110); andResetFailedAttemptsAsynconce the password verifies (:115). The counter key ispassword-change:{userId}, built by the privateProtectionKeyhelper with the id rendered underCultureInfo.InvariantCulture(:144-145). The constructor documentation gives the two reasons it is not keyed by email:IAuthUserexposes no address, and a separate key keeps a change-password lockout from locking the owner out of sign-in (:47-53,:138-143).[Rubric §11: Security]assesses credential handling. Four properties are visible in the code. Repeated guesses are throttled by the lockout above before the hasher is even called (:101-106). The current password is verified before anything is written (:108), and the failure is anUnauthorizederror with a stable code rather than a message that distinguishes "no such user" from "wrong password" at this layer (:95-99,:108-113). Nothing in the handler ever logs the plaintext, the hash or the salt: the success log carries only the user id (:147-148). Hashing itself is delegated toIPasswordHasher, whose contract returns a hash and a fresh salt as a tuple (IPasswordHasher.cs:11), the shape ADR-032 fixes. A successful change also revokes every live refresh session on the account through the requiredIRefreshSessionStore, via the sharedRefreshSessionRevocationhelper (:126-128, comment at:121-125), so a stolen refresh chain cannot outlive the rotation that was meant to remediate it (ADR-097). The revocation is persisted before the explicit password save (:130, the M240 comment at:123-125): a revoke failure throws ahead of the save, so the user can simply retry, and that save also carries the already-mutated user. The pair is atomic only when the session store and the user repository share a data source (class remarks,:25-36). Only thetimeProviderparameter defaults tonull; the base caches it in a private_timeProviderfield, falling back toTimeProvider.System(:65), and a caller must supply the refresh-session store and the lockout service explicitly.[Rubric §4: DDD]assesses whether business rules live in the domain. The handler never mutates the user's fields: it callsuser.ChangePassword(newHash, newSalt)(:118) and returns whateverResultthe aggregate produced, so an aggregate invariant (for example refusing rotation on a deleted account) short-circuits the save without the handler knowing the rule exists.Walkthrough: two protected members, the handler method, and two private helpers.
- Primary constructor (
:55-61):unitOfWork,passwordHasher,logger, the requiredrefreshSessionsandloginProtection, and the optionaltimeProvider. The logger is typed as the non-genericILoggerso a subclass can pass its ownILogger<TAppHandler>and keep the log category app-specific while the message text stays in the base's own[LoggerMessage]declaration (ADC passesILogger<ChangePasswordHandler>atMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordHandler.cs:27). UnitOfWork(:68): aprotectedpass-through over the captured parameter, exposed so an app subclass can enlist further aggregates in the same unit of work.HandlerName(:75):protected virtual, defaulting toGetType().Name. Because each app keeps a subclass namedChangePasswordHandler, that name is what thesourcefield of every returned error reports (:70-74).HandleAsync(TCommand, CancellationToken)(:78-136): null-guards the command (:82); takes the write repository viaGetRepository(:84) because this path saves; loads bycommand.UserId(:85) and returnsError.NotFoundstamped with the handler name and the aggregate type name when the account is missing (:88); rejects a credential-less account (:95-99); builds the counter key and checks the lockout (:101-106); verifies the current password, incrementing the counter and returningError.Unauthorized("Auth.InvalidCurrentPassword", ...)on mismatch (:108-113); resets the counter (:115); hashes the new password into a(newHash, newSalt)tuple (:117); calls the aggregate (:118); and only on success revokes refresh sessions (:126-128), then saves (:130) and logsPasswordChanged(:132). The aggregate's result is returned either way (:135), so a domain failure propagates unchanged.ProtectionKey(UserIdentifierType)(:144-145):private static, thepassword-change:counter key described above.PasswordChanged(ILogger, UserIdentifierType)(:147-148): the source-generated Information-level audit line, "User {UserId} password changed".
- Primary constructor (
Why it's built this way: one copy of the workflow, with app variation expressed as generic parameters and one virtual hook, keeps the two apps from diverging silently, and it is the standing preference for reusable infrastructure in this workspace. Keeping the command record app-side is not a compromise but the correct boundary: the record is where CQRS pipeline policy is declared, and that policy is genuinely per app (
ChangePasswordHandlerBase.cs:19-24).Where it's used: subclassed once per app, each subclass empty apart from the constructor forwarding, and both forward the lockout service (
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordHandler.cs:24,:30;MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordHandler.cs:28,:34). Both subclasses are picked up as scoped command handlers byScanModuleApplicationServices<TAssemblyMarker>()(seeDependencyInjection) and are then wrapped by the decorator pipeline. The workflow is pinned directly byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/ChangePasswordHandlerBaseTests.cs:18, which drives it through a test double subclass that also takes anILoginProtectionService(:254-260).Caveats: new-password strength is not checked here. Both apps' commands additionally implement
ICommandWithRequest<ChangePasswordRequest>(ChangePasswordCommand.cs:13in ADC,:13in Store), which routes the payload through the Validating decorator before the handler runs, so the base can assume a syntactically valid request. The lockout counter is reset as soon as the current password verifies (:115), before the aggregate is asked to accept the new one (:118), so an aggregate rejection after a correct password still clears the count. Neither app's command implementsITransactional, so the singleSaveChangesAsyncat:130is the whole atomic unit for the aggregate write (it runs after the session revocation,:126-128); the lockout counter is written throughILoginProtectionService, outside it.
ChangePreferencesHandlerBase<TUser, TCommand>
MMCA.Common.Application ·
MMCA.Common.Application.Users.UseCases.ChangePreferences·MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:23· Level 8 · class (abstract)
What it is: the shared preference-write workflow. Load the account, merge the partial request over the stored values, let the aggregate apply its invariants, and persist on success (
ChangePreferencesHandlerBase.cs:23,:39-62).Depends on:
IUnitOfWorkand anILogger(:22-24); implementsICommandHandler<in TCommand, TResult>overResult(:24). Constraints:TUseris anAuditableAggregateRootEntity<TIdentifierType>implementingIUserPreferences(:25), andTCommandis anIUserScopedCommand<out TRequest>carrying aChangePreferencesRequest(:26). Also usesError, and logs through a private source-generated[LoggerMessage]method,PreferencesChanged(:64-65), hence thepartialdeclaration (:22). Externals:Microsoft.Extensions.Logging(:1).Concept introduced: null means "leave alone", and where that rule is enforced. The request record is nullable in both fields on purpose: the app-bar culture switcher sends only a culture and the theme toggle sends only a theme (
MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ChangePreferencesRequest.cs:3-10). A naive handler that passed both fields straight to the aggregate would clear whichever one the caller omitted. The merge therefore happens in exactly one place, at the call into the aggregate:command.Request.Culture ?? user.PreferredCultureand the matching line for the theme (:52-54). The domain interface documents the same contract from its side, so an aggregate author knows thatUpdatePreferencesalways receives both values fully resolved (IUserPreferences.cs:18-25).[Rubric §15: Best Practices & Code Quality]assesses whether a rule has one home. This merge has exactly one, with one test suite, so a change to it (say, adding a third preference) is made once for both apps rather than in two repositories in lockstep.[Rubric §24: Forms, Validation & UX Safety]assesses whether a partial update can destroy data the user did not touch. The null-coalescing merge is the guarantee that it cannot: switching the theme never wipes a stored culture, which is exactly the failure the UI's two independent controls would otherwise produce (ADR-027 culture, ADR-028 theme).Walkthrough: same shape as the password base, with fewer collaborators.
- Primary constructor (
:22-24):unitOfWorkandlogger; no hasher, lockout or session store, since nothing here is credential material. UnitOfWork(:29) andHandlerName(:36): the same two protected members, with the same rationale (an app subclass namedChangePreferencesHandlerreports that name as the errorsource,:31-35).HandleAsync(TCommand, CancellationToken)(:39-62): null-guard (:43); write repository viaGetRepository(:45); load bycommand.UserId(:46);Error.NotFoundstamped with handler and aggregate names when missing (:49); the merged call touser.UpdatePreferences(...)(:52-54); and, only when the aggregate succeeded,SaveChangesAsyncplus thePreferencesChangedlog (:55-59). The aggregate's result is returned unchanged (:61).
- Primary constructor (
Why it's built this way: identical to the rationale for
ChangePasswordHandlerBase<TUser, TCommand>: ADC'sChangePreferencesCommandis a plainIUserScopedCommand<ChangePreferencesRequest>(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommand.cs:11-12) and so is Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommand.cs:11-12), neither implementsICacheInvalidating, and the record stays app-side while only the payload record (ChangePreferencesRequest) is shared (ChangePreferencesHandlerBase.cs:15-20).Where it's used: subclassed by
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandler.cs:17,:20andMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandler.cs:16,:19, both empty subclasses that exist only to fix the generic arguments and carry the class name. Invoked fromUserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>, which builds the app's command through a factory hook and returns204 No Contenton success (UserAccountAuthControllerBase.cs:126-132). Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBaseTests.cs:16through a test subclass (:108-109).
CreateMigrationProofTable
MMCA.Common.Infrastructure.Tests.MigrationsFixture ·
MMCA.Common.Infrastructure.Tests.MigrationsFixture·MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests.MigrationsFixture/CreateMigrationProofTable.cs:24· Level 13 · class (sealed)
What it is: a real, committed EF Core migration against the framework's single SQLite context. It creates one table,
MigrationProof, and exists so the framework's migration-apply path can be proved against the kind of artifact a consumer would actually commit rather than against a mock (CreateMigrationProofTable.cs:24,:39-47).Depends on:
SqliteDbContext, named in the[DbContext]attribute (:22). Externals: EF Core'sMigrationbase class,MigrationBuilder, and theDbContextAttribute/MigrationAttributepair fromMicrosoft.EntityFrameworkCore.Migrationsand.Infrastructure(:1-2). Its project takes a singleProjectReferenceonMMCA.Common.Infrastructureand is markedIsPackable=false(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests.MigrationsFixture/MMCA.Common.Infrastructure.Tests.MigrationsFixture.csproj:3,:6).Concept introduced: a test fixture that has to live in its own assembly. EF Core does not discover migrations by convention over the whole app: it scans one nominated migrations assembly and matches the migrations in it to a context by the
[DbContext]attribute each one carries (:22). The framework declares exactly one SQLite context class (ADR-006), so any migration compiled intoMMCA.Common.Infrastructure.Testswould immediately be "pending" for every other test in that assembly that names it as the migrations assembly. One of those tests,DbContextFactoryMigrationTargetTests, rests its whole argument on the test assembly declaring none. The two facts cannot coexist in one assembly, so the migration was given its own tiny library and only the tests that opt in by naming it ever see it (:12-18). The class remarks state that reasoning in the code itself.There is a second, smaller lesson in what the file does not contain. No
.Designer.csand no model snapshot accompany it: neither is needed to apply a migration at run time, and both exist only sodotnet ef migrations addcan diff the next one (:19-21). The direct consequence shows up inUp, where the column types are written out by hand because an empty target model supplies nothing (:37-38).[Rubric §14: Testability]assesses whether the hard parts of the system can be exercised for real rather than asserted about. Migration application is exactly such a part: it is startup behavior against a live provider, and mocking it proves nothing. This fixture makes it testable by supplying the one input the production path needs (a committed migration in a nominated assembly) while isolating it from every other test through an assembly boundary.[Rubric §8: Data Architecture]assesses schema-change discipline. The two public constants are the contract this fixture offers its tests: the migration id recorded in__EFMigrationsHistory(:27) and the table name that proves the schema, not just the history row, was touched (:30). Asserting on both is what separates "EF wrote a history row" from "the schema actually changed".[Rubric §17: DevOps]assesses whether deployment behavior is verified rather than assumed. The"None"initialization strategy, which is what a deployed host runs, has to refuse to start when the schema is behind the code and has to name the pending migration in the failure so an operator knows what to apply. That guard can only be exercised against a genuinely pending, genuinely named migration, which is what this type provides (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/DatabaseInitializationExtensionsTests.cs:145,:168).Walkthrough: two attributes, two constants, and the migration pair.
[DbContext(typeof(SqliteDbContext))](:22): the binding EF uses to decide which context this migration belongs to.[Migration(MigrationId)](:23): the id EF records and reports. Passing the constant rather than a literal is what lets the tests assert onCreateMigrationProofTable.MigrationIdinstead of repeating the string.MigrationId(:27):"20260831000001_CreateMigrationProofTable", the timestamp-prefixed form EF expects and the value written into__EFMigrationsHistory.TableName(:30):"MigrationProof", the tableUpcreates and the evidence a test queries for.Up(MigrationBuilder)(:33-48): null-guards the builder (:35), then a singleCreateTablewith an autoincrementinglongIdcarrying theSqlite:Autoincrementannotation (:43-44), a non-nullstring Name(:45), and a primary key namedPK_MigrationProofbuilt from the same constant (:47). Every column type is stated explicitly for the empty-target-model reason above.Down(MigrationBuilder)(:51-56): drops the table, so the migration is reversible and a test that applies it leaves nothing conceptually stranded.
Why it's built this way: the framework's migration story is a production concern, not a unit test.
MigrateAsync()onDbContextFactoryis the same call a host makes for the"Migrate"strategy (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/MigrationApplyProofTests.cs:22-26), and a proof of it needs a real migration, a real SQLite file, and a real history table. Nominating the assembly is configuration, not code: a data source points at it throughDataSourceEntrySettings.SqliteMigrationsAssembly(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceEntrySettings.cs:55), which is exactly how the tests wire this fixture in (MigrationApplyProofTests.cs:41-42,:57-58).Where it's used: by two test classes, in two different assemblies, for two different halves of the same behavior.
MigrationApplyProofTestsapplies it throughDbContextFactoryand asserts the history row, the created table, and that nothing stays pending (MigrationApplyProofTests.cs:94-106); that asking what is pending applies nothing (:110-120); and that a secondMigrateAsyncover an up-to-date database is a no-op rather than a re-apply whoseCREATE TABLEwould collide (:124-133).DatabaseInitializationExtensionsTestsuses it for the production guard inDatabaseInitializationExtensions: the"None"strategy must throw naming the pending migration and must apply nothing on the way out (DatabaseInitializationExtensionsTests.cs:154-155,:167-174). Its deliberate non-consumer isDbContextFactoryMigrationTargetTests, which needs a migrations assembly that declares nothing.Caveats: the assembly is a test fixture, never shipped:
IsPackable=false(MMCA.Common.Infrastructure.Tests.MigrationsFixture.csproj:3) and it is listed inMMCA.Common.slnxunderTests/(MMCA.Common/MMCA.Common.slnx:37), so nothing in the published packages carries this migration. Because there is no model snapshot,dotnet ef migrations addcannot meaningfully extend this assembly: a second migration here would have to be hand-written the same way.
⬅ gRPC & Inter-Service Contracts • Index • Common UI Framework (MudBlazor components, theme, base pages) ➡