Onboarding guide
7. Persistence & EF Core
What this group covers. This is the framework's data-access engine: everything between a domain
aggregate and a row in a database. It is the single largest group in the guide because it carries a
lot of load. One abstract ApplicationDbContext base with a sealed subclass
per engine (SQLServerDbContext,
PostgreSQLDbContext, CosmosDbContext,
SqliteDbContext) and a stateless engine registry
(IDataSourceEngine, DataSourceEngines) that answers every
engine-specific question as data; four EF Core save interceptors that turn a plain
SaveChangesAsync into audit stamping, tenant enforcement, transactional domain-event capture, and a
field-level change trail; a small repository family behind an interface-segregated contract
(IReadRepository<TEntity, TIdentifierType>,
IWriteRepository<TEntity, TIdentifierType>,
IRepository<TEntity, TIdentifierType>) coordinated by a
UnitOfWork, with the query-shaping helpers
(SpecificationEvaluator, KeysetQueryBuilder)
that turn a specification or a cursor into SQL; a durable job queue
(InternalCommandMessage,
InternalCommandScheduler,
InternalCommandProcessor) that commits a unit of deferred work in the
same transaction as the change that asked for it; a data-source routing layer that lets every entity
resolve to its own physical database ("database per service") and every tenant optionally to its own
copy of it; three model-finalizing conventions that keep that routing, its unique indexes and its
delete behavior honest; an engine-portable
entity-configuration hierarchy; a model-contributor extension point
(IModelContributor) through which every optional framework table joins the model;
and a supporting cast of value converters, an
encryption converter, seeders, and design-time factories. The group also owns the settings objects the
whole engine binds from configuration (PersistenceSettings,
ConnectionStringSettings, DataSourcesSettings,
TenancySettings, AuditTrailSettings,
InternalCommandsSettings) plus the two settings validators and the one
navigation-coverage check that fail a boot on a misconfiguration, and the Application-layer storage and push
contracts whose implementations are composed in
Group 14. The whole thing is the
[Rubric §8, Data Architecture] chapter of the codebase, and it leans hard on
[Rubric §7, Microservices Readiness] and [Rubric §3, Clean Architecture].
One base context, one class per engine, one instance per database
ApplicationDbContext
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:44)
is an abstract primary-constructor class over EF's DbContext. It holds the cross-cutting model
configuration every engine shares. It applies a global soft-delete query filter to every non-owned
IAuditableEntity using a runtime-built
expression tree, registered as a named "SoftDelete" filter (HasQueryFilter at
ApplicationDbContext.cs:703, name at :494); it applies a second named "Tenant" filter to every
non-owned ITenantEntity
(ApplicationDbContext.cs:815, name at :497); it configures the RowVersion
optimistic-concurrency token by the engine's RowVersionStrategy, mapped as a
SQL Server rowversion or as a plain token the audit interceptor stamps on PostgreSQL and SQLite
(ConfigureConcurrencyTokens at :613, called at :435); and it maps the three framework
bookkeeping tables every relational database carries
(OutboxMessage at :684-690,
InboxMessage at :759-762,
InternalCommandMessage at :803-809), each with the filtered
indexes its poll path and its retention sweep need (IX_OutboxMessages_Pending at :732,
IX_OutboxMessages_Processed at :739, the keyed-ordering index IX_OutboxMessages_Ordering at
:751, IX_InboxMessages_MessageId_Consumer at :780, IX_InboxMessages_ProcessedOn at :785,
IX_InternalCommands_Pending at :833, IX_InternalCommands_Processed at :840,
IX_InternalCommands_DeadLettered at :845). Those three are deliberately not optional: they are
mapped into every relational source whether or not this host drains them, so flipping
InternalCommands:Enabled is never a migration (:793).
Every other framework table is optional, and none of them is named in the base context. Each arrives
through the IModelContributor extension point
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/IModelContributor.cs:40,
ADR-148):
a contributor declares a ModelContributorPhase (:46), answers
AppliesTo(PhysicalDataSource) once per context instance (:56), and adds its mapping in
Configure(ModelBuilder, DataSource) (:67). The feature's own AddX call registers it as a
singleton with TryAddEnumerable, so a new optional table is a new contributor, never an edit to the
base (:12-20). The base resolves every registered contributor in OnConfiguring, keeps those whose
AppliesTo accepts this context's physical source, and orders them by phase with a stable sort so
contributors sharing a phase keep registration order (ApplicationDbContext.cs:550-554); Cosmos gets an
empty list, because it never runs the base model pipeline (:329-332, IModelContributor.cs:35-38).
OnModelCreating then runs them in two passes through ApplyModelContributors (:457-464): the
ModelContributorPhase
(.../DbContexts/ModelContributorPhase.cs:8) value BeforeEntityPasses (:16) runs beside the module
configurations, ahead of the soft-delete, tenant and concurrency passes, so an auditable or tenant-owned
contributed table gets its filter and its token (ApplicationDbContext.cs:649-653), and
AfterEntityPasses (ModelContributorPhase.cs:23) runs after the three bookkeeping tables, for a table
no pass may touch (ApplicationDbContext.cs:664-666). This group ships six of them, each beside the
model-builder extension that holds its mapping:
| Contributor | Phase | AppliesTo (the gate) |
|---|---|---|
AuditTrailModelContributor (.../AuditTrail/AuditTrailModelContributor.cs:17) |
After (:20) |
AuditTrail:Enabled only, so every relational source, because a trail row must commit with the change it describes and a transaction does not span databases (:23, reasoning at :10-14); maps IX_AuditTrailEntries_Entity and IX_AuditTrailEntries_ChangedOn (:40, :46) |
RefreshSessionModelContributor (.../Auth/RefreshSessionModelBuilderExtensions.cs:121) |
After (:124) |
RefreshSessions:Enabled AND the source its DataSourceName names (:127-129) |
PermissionGrantModelContributor (.../Auth/PermissionGrantModelBuilderExtensions.cs:84) |
After (:87) |
only the source Authentication:PermissionGrants:DataSourceName names (:90-91): the AddStoredPermissionGrants registration itself is the opt-in, because a second flag would be a second way to say the same thing (:75-81) |
ViewAsGrantModelContributor (.../Auth/ViewAsGrantModelBuilderExtensions.cs:73) |
After (:76) |
ViewAs:Enabled AND ViewAs:HostsGrantStore AND the named source (:79-82) |
PasskeyCredentialModelContributor (.../Auth/PasskeyCredentialModelBuilderExtensions.cs:72) |
After (:75) |
Passkeys:Enabled AND the named source (:78-80) |
MachineClientModelContributor (.../MachineClients/MachineClientModelBuilderExtensions.cs:71) |
Before (:74) |
MachineClients:Enabled AND the named source (:77-79); Before because a client is an auditable entity the passes must see |
The job table (ScheduledJobModelContributor),
the feature-flag override table
(FeatureFlagOverrideModelContributor)
and the webhook subscription table
(WebhookSubscriptionModelContributor)
use the same extension point from their own groups. A host that registers none, or whose contributors
all decline this source, builds exactly the base model, so its migrations never see a table it did not
opt into (ApplicationDbContext.cs:74-80). The rule that keeps this safe is the model cache: the key
carries the applying contributor types, never their state, so Configure must be a pure function of
the contributor's type and the engine, and anything a host setting should change belongs in AppliesTo
(IModelContributor.cs:27-33, key at ApplicationDbContext.cs:114).
Its SaveChangesAsync(userId, ...) overload (ApplicationDbContext.cs:206-220) is the one entry
point handlers care about: it stashes the current user id in CurrentSaveUserId so the audit
interceptor can read it, delegates to base, then clears it in a finally so a later internal save
cannot silently reuse the previous caller's identity (:202, :207-212). The base also overrides the
save overloads purely to run change detection once per save and suppress it for the rest,
through the DetectChangesOnce helper and its DetectChangesScope disposable
(:219-224, :254, helper at :279-287): each interceptor's ChangeTracker.Entries<T>() call would
otherwise trigger a full DetectChanges, so a save paid three snapshot comparisons where one
suffices, and the previous auto-detect setting is restored when the scope is disposed (:289-292).
The design decision that shapes this whole group is stated in the base's own doc comment: one
context class per engine, one instance per physical data source (ApplicationDbContext.cs:32-38).
The same SQLServerDbContext class
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/SQLServerDbContext.cs:15)
is instantiated once per SQL Server database, each instance carrying a different
PhysicalDataSource (connection string, per-engine migrations assembly, Cosmos
database name). To keep EF from silently reusing the first-built model for every database,
DataSourceModelCacheKeyFactory
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/DataSourceModelCacheKeyFactory.cs:23)
keys EF's model cache by context type, physical source name, the applying model contributors, the
declared strongly typed identifier wrappers and the design-time flag (:26-33), and is installed by
the base in OnConfiguring (ApplicationDbContext.cs:577). This is deliberately
not a per-module context split: one sealed context per engine over the abstract base is
ADR-006's ruling. Each instance
also exposes the engine it targets as an internal Engine property resolved through
DataSourceEngines (ApplicationDbContext.cs:59), which is how the base, the
interceptors and the factory ask an engine question without naming an engine.
SQLServerDbContext adds the provider-specific touches: a per-environment command timeout read from
PersistenceSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/PersistenceSettings.cs:10, bound from
the Persistence section at :13, range-checked between 1 and 600 seconds and defaulting to the same
30 the framework applied implicitly before the section existed, :21-22) rather than
ADO.NET's silent 30-second default (SQLServerDbContext.cs:55, with the settings object resolved once
into a field at :36-37 using GetService so the design-time provider, which registers no options at
all, cannot be made to throw), transient-fault retry (EnableRetryOnFailure with 5 attempts and a
10-second cap, :63-66), and a suppressed PendingModelChangesWarning (:79) so an extracted service
that registers only its own module's entity configurations starts cleanly against a migration snapshot
that captures every module's tables. That warning suppression is a direct
[Rubric §7, Microservices Readiness] decision, and the source comment states the trade-off plainly:
monolith hosts lose the "you forgot a migration" safety net, so CI is expected to run
dotnet ef migrations has-pending-model-changes as a separate gate (:68-78). The retry comment also
carries a rule the rest of the group depends on: with retry-on-failure enabled a manual
BeginTransactionAsync must run inside Database.CreateExecutionStrategy().ExecuteAsync (:60-62).
SqliteDbContext (.../DbContexts/SqliteDbContext.cs:12) is the same shape with
UseSqlite and its own migrations assembly (:24-33), and
CosmosDbContext (.../DbContexts/CosmosDbContext.cs:15) deliberately does not
call base.OnModelCreating, because the relational bookkeeping tables have no place in a document
store; it re-applies only the filters it needs (:139-145).
PostgreSQLDbContext (.../DbContexts/PostgreSQLDbContext.cs:24) is the
fourth engine class (ADR-113),
and its mapping conventions deliberately match SQLServerDbContext rather than PostgreSQL house
style: PascalCase identifiers and the module schema, so an entity configuration body is portable
between the two engines with no edits, and a consumer that wants snake_case adds a naming plugin in
its own host (:16-22). It maps every DateTime to timestamp with time zone (:35, applied at
:122-125) through
UtcDateTimeConverter
(.../Persistence/Conversions/UtcDateTimeConverter.cs:25), because Npgsql refuses to write a value
whose Kind is not Utc and a consumer property, a JSON round-trip or a legacy row can arrive
Unspecified; the process-wide Npgsql.EnableLegacyTimestampBehavior switch is rejected precisely
because it changes the mapping for connections the framework does not own and stores timestamps
without a zone (:5-24). Its connection is the one place an engine class reaches past a connection
string. OnConfiguring asks NpgsqlDataSources
(.../DbContexts/NpgsqlDataSources.cs:19) for a shared NpgsqlDataSource and hands EF that when one
exists, or the raw connection string when not, with the same migrations-assembly, command-timeout and
retry options on both paths (PostgreSQLDbContext.cs:60-71, options at :82-106). A data source
exists only once a host registers an
INpgsqlDataSourceConfigurator
(.../DbContexts/INpgsqlDataSourceConfigurator.cs:23), the hook for a password provider (an RDS IAM
token, a vault lease), a client certificate callback or a type mapping (:5-10).
AddNpgsqlDataSourceConfigurator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Persistence.cs:24) adds the
configurator, idempotent per configurator type, and a keyed singleton under KeyedService.AnyKey
whose key is the connection string (:20, :28-34), so the container itself is the cache: one data
source per distinct connection string, built on first use with every registered configurator run on
its builder, and disposed with the container (NpgsqlDataSources.cs:42-56). Keying by a plain string
is what lets the PostgreSQL readiness check in MMCA.Common.Aspire reach the same instance without
referencing this package (:13-17). The AWS and GCP adapters register their IAM-token configurators
this way (MMCA.Common/Source/Hosting/MMCA.Common.Aws/AwsServiceCollectionExtensions.cs:140,
MMCA.Common/Source/Hosting/MMCA.Common.Gcp/GcpServiceCollectionExtensions.cs:116). A host with none
registered resolves null and keeps the connection-string path, and so does the design-time provider
behind dotnet ef, which cannot resolve keyed services (NpgsqlDataSources.cs:21-32); the context
never holds the data source in a field, because the container owns and disposes it
(PostgreSQLDbContext.cs:47-53). One more base-context decision belongs here:
SensitiveDataLoggingGate
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SensitiveDataLoggingGate.cs:24)
decides whether EF may render parameter values into logs and exception messages, and the answer is
an AND rather than a single switch: the host must both ask for it and report itself as Development
(ApplicationDbContext.cs:563, :376-380). A null IHostEnvironment, which is what design-time
tooling and a directly-constructed test context have, counts as not Development, so unknown fails
closed (SensitiveDataLoggingGate.cs:10-22). That is [Rubric §11, Security] in one helper.
SaveChanges as an interceptor pipeline
The base context resolves its interceptors from DI in OnConfiguring
(ApplicationDbContext.cs:512-545), and registration order is execution order. The audit
interceptor runs first, the tenant interceptor between it and the domain-event interceptor (so the
outbox rows describe an entity whose tenant is already final, :300-312), and the change-trail
interceptor last, because it diffs the final values (:314-322). Two of the four are resolved with
GetService rather than GetRequiredService: a directly-constructed test context or a host that
never called AddAuditTrail must still build, and their absence has to read as "the feature is off"
rather than fail every context construction.
AuditSaveChangesInterceptor
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/AuditSaveChangesInterceptor.cs:38)
runs on SavingChanges: it walks every tracked
IAuditableEntity, stamps CreatedOn/By plus
LastModifiedOn/By on Added (:79-83), and on Modified marks the two Created* properties
unmodified before re-stamping LastModified* (:90-94), reading the timestamp from an injected
TimeProvider and the user id from CurrentSaveUserId (falling back to default as the
system-operation sentinel, :65-66). An owner whose only edit is to an owned value object (an
OwnsOne address, an OwnsMoney price) is still Unchanged to EF, because the change is tracked on
the owned entry, so the interceptor asks OwnedDependents.HaveChanges and stamps
that owner as Modified (:71-75). That helper
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/OwnedDependents.cs:12,
HaveChanges at :24-26) walks the owner's owned references and owned collection items for an entry
being inserted, updated or deleted, and its remarks name the one blind spot: an optional owned
reference set to null leaves no entry to read, so clearing one is not detected (:18-21). It also
writes the soft-delete stamps, and it drives them off
the transition of the IsDeleted flag rather than its value: DeletedOn/By are written when the
flag goes false to true and cleared when it goes back (StampSoftDeleteTransition, doc at :125-129, with the original value read by WasDeleted at
:122-123), so a later update to an already-deleted row keeps the stamps of the delete that produced
it, exactly as CreatedOn/By survive every update. This is why the domain declares audit fields with
private setters and never writes them: the interceptor sets them centrally through
entry.Property(...).CurrentValue, bypassing setter visibility. On an engine whose
RowVersionStrategy is ClientStamped (PostgreSQL, SQLite) it also writes a fresh
RowVersion on every insert and update, so the UPDATE's WHERE clause detects a concurrent writer where no
server-generated row version exists (:67, :88, :97, StampRowVersion at :113-119). That is the
[Rubric §12, Performance & Scalability] payoff, one enforcement point instead of copy-paste in every
handler.
DomainEventSaveChangesInterceptor
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:59)
is the producer end of the outbox, and it is the most subtle type in the group. On SavingChanges it
snapshots each tracked IAggregateRoot and its
pending IDomainEvents into an
AggregateCapture record (:262-266, record at :482), then writes an
OutboxMessage row for each event into the same context, so
the events land in the database in the same transaction as the aggregate changes (:248-322). The
routing split happens right there: an
IIntegrationEvent gets a row but no in-process
dispatch (its row stays unprocessed so the OutboxProcessor
publishes it over IMessageBus), while a local event gets both
a row and the fast in-process path (:291-304). On the async path that local row is inserted
already leased: NewLocalLease builds a LocalLease record struct (:502) of now
plus Outbox:LeaseSeconds under a fresh token (:348-349, the seconds read once into a field at
:71), and ApplyLocalLease writes it onto the row's LockedUntil and LockToken (:338-345). No
replica's poller can therefore deliver the event a second time while this process is still dispatching
it, a crash leaves the row to be retried once the lease expires, and a failed dispatch hands it back
early (:20-24). Only the async path leases, because only it dispatches in-process (:101-103). Before
capturing, DiscardAbandonedCapture detaches the Added outbox rows left by a previous
SavingChanges that never reached SavedChanges (:356-373, called at :254), which is what stops an
execution-strategy retry from writing a second row per event and publishing every integration event
twice. The captured state, including the lease token its local rows were written under, is parked in a
CapturedState record (:492) held in a ConditionalWeakTable keyed by context
(:78, stored at :321), so it is cleaned up automatically when the context is disposed. A third weak
table (:94) holds a per-context capture exclusion set: BeginCaptureExclusion / EndCaptureExclusion
(:214, :230) let DbContextFactory name exactly the entries it hides from an
explicit-key insert round, so an event is never serialized and cleared a round before the insert that
justifies it. The exclusion is by instance rather than by entity state on purpose: a state-based filter
would also drop events raised on an already-saved aggregate, which is how the identity module publishes
its registration events (:207-211).
After the save, the post-save path DispatchAndFinalizeAsync
(DomainEventSaveChangesInterceptor.cs:379-396, reached from SavedChangesAsync at :123-131) does
one of two things. With no ambient transaction it flushes immediately through FlushStateAsync
(:403-462): dispatch local events through
IDomainEventDispatcher, remove exactly the
captured events from their aggregates, mark the local outbox rows processed through
OutboxFinalizer, and signal the outbox for integration
events (:426-441). With an active transaction it removes the captured events (so a second save inside
the same transaction cannot re-capture them) and defers the same FlushStateAsync call through
DeferUntilCommit (:386-393), which appends it as plain post-commit work to a list held in a second
weak table (:86, method at :188-189). That method is the one post-commit hook for in-process
delivery: the save interceptor and InProcessEventBus both defer through it, so the two cannot
disagree on when a transactional unit's events reach their handlers (:177-185).
DbContextFactory then calls the static FlushDeferredAsync only after a
successful commit, running the deferred work in the order it was deferred (:166-175, called at
DbContextFactory.cs:669), and DropDeferred on rollback or an execution-strategy retry (:197,
reached through DbContextFactory.cs:890-892). That is what keeps handler side effects from acting on
state that could still roll back, and what keeps a retrying execution strategy from dispatching the
same events once per attempt. Note the precision of the clearing: the interceptor calls
RemoveDomainEvents(capture.Events) rather than clearing the aggregate wholesale (:464-474), so an
event a handler raises on the same aggregate during in-process dispatch survives to a later capture
instead of being wiped. The dispatch loop itself lives in
InProcessDispatch, which the interceptor calls at
DomainEventSaveChangesInterceptor.cs:410-423. For outbox-backed local events, DispatchBackedAsync
dispatches one event at a time and reports each outcome, so a handler failure is settled per event: the
rows of the events that succeeded are marked processed, and a failed event's row (plus the later rows
sharing its ordering key, held back unattempted) is returned as undelivered
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/InProcessDispatch.cs:16-74).
The interceptor then releases the lease those undelivered rows were inserted under and signals the
outbox, so the processor retries them after the processing delay rather than after the full lease
(DomainEventSaveChangesInterceptor.cs:430-437). The release runs through
InProcessDispatch.ReleaseLeaseAsync, guarded by the save's lease token and run with
CancellationToken.None, so a dispatch that failed by cancellation still hands its rows back; a failed
release is itself only logged, and the rows then wait out the lease (InProcessDispatch.cs:111-142,
:150-151). The interceptor's own catch is reached only by a cancellation or a failed finalize: it logs,
releases every local row of the save, and signals the outbox
(DomainEventSaveChangesInterceptor.cs:443-456). Local events that no outbox row backs (the outbox is
off, or the engine is not relational) take DispatchUnbackedAsync instead (:397-401), because nothing
will ever retry them: it dispatches one event at a time and logs each failure at Error naming the event
type, so one throwing handler cannot take the later events of the save down with it
(InProcessDispatch.cs:90-109, per-event catch at :102-107). The isolation is per event, not per
handler, and the doc comment says so: a host whose handlers must all run, or run again, enables the
outbox (:76-84). The synchronous SavedChanges path cannot await a dispatcher at all, so it removes
the captured events, signals the outbox, and leaves delivery entirely to it
(DomainEventSaveChangesInterceptor.cs:144-158). Two conditions take the everything-in-process branch
instead: Cosmos DB has no relational outbox table, so the interceptor asks the context's engine whether
it is relational (DataSourceEngineCapabilities.IsRelational, read at :146 and :262), which is
false only for CosmosDbContext's engine; and a host can turn the outbox off
outright, which the interceptor reads once from the message-bus options into _outboxEnabled (:69)
and honors at the same branch (:262, :297-303). This split, atomic persistence plus best-effort
immediate dispatch with a durable fallback, is the at-least-once contract of
ADR-003; the consumer end lives
in Group 04.
Deferred work, the internal-command queue
The same "write it in the transaction, run it afterwards" reasoning the outbox applies to events is
applied to work by the internal-command queue
(ADR-114).
InternalCommandMessage
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandMessage.cs:20)
is one unit of deferred work persisted to the InternalCommands table, and its doc comment states the
kinship plainly: like OutboxMessage it is framework bookkeeping rather than domain state, so it is
deliberately not an IAuditableEntity, carries no soft-delete flag (no global query filter applies to
it), no audit stamps and no concurrency token; its concurrency control is an explicit claim lease
(:9-19). InternalCommandScheduler
(.../InternalCommands/InternalCommandScheduler.cs:36) writes that row on the same scoped
IDbContextFactory the calling handler's repositories use, which is the whole
atomicity story: inside an ITransactional command the factory has already begun a transaction on
every context it hands out, so the row commits with the aggregate change or rolls back with it, and
outside a transaction the row is saved immediately and the processor is signalled (:19-25, :118-125).
An enrolled row cannot signal at enrollment, because nothing can read it until the commit, so the
scheduler records the wake it owes in EnrolledCommandWake
(.../InternalCommands/EnrolledCommandWake.cs:14, Defer called at InternalCommandScheduler.cs:113), a
static class over a ConditionalWeakTable keyed weakly on the context, like the deferred domain-event
dispatch (EnrolledCommandWake.cs:7-16). The unit of work that owns the transaction calls Release
once every commit has succeeded, which signals each distinct processor wake exactly once however many
rows or contexts enrolled (:24-49), and Drop on rollback or retry (:51-53), so a rolled-back row
never wakes the processor and a context nobody commits leaves nothing behind. Each row
also carries an InternalCommandOrigin
(.../InternalCommands/InternalCommandOrigin.cs:16): the scheduling user, roles, tenant, correlation
id and trace context, because without it a deferred command would run as an anonymous tenant-less
system call, which is both an authorization hole (an IRequiresPermission command would be denied)
and an audit hole (its writes would carry the system sentinel, :1-9). The snapshot is taken by the scoped
InternalCommandOriginCapture
(.../InternalCommands/InternalCommandOriginCapture.cs:21, Capture at :28-39), which the scheduler
calls as it builds the row (InternalCommandScheduler.cs:40, :88). It is scoped like the request
services it reads, because the snapshot must describe this request's caller, and it flattens roles through
the same helper the outbox capture uses, so the two hops store one shape
(InternalCommandOriginCapture.cs:13-17).
InternalCommandProcessor
(.../InternalCommands/Processing/InternalCommandProcessor.cs:43) is the drain: a background service
that claims due rows with a lease, executes each in a fresh DI scope, and records the outcome. Every
relational physical source this host uses has its own queue table and each cycle drains them all, so a
service only ever runs the work queued in its own databases, and the lease is what makes scale-out
safe, since two replicas racing for a row issue the same conditional update and exactly one matches
(:20-35). Execution is explicitly at-least-once: a replica that dies after its handler committed and
before the row was stamped releases the row when the lease expires and the command runs again, which
is the same idempotency contract the outbox already places on event handlers (:30-34). The batch claim is renewed row by row just
before each command runs, in a statement guarded on the claim token, so a slow batch cannot outlive its
lease and let another replica start a later row, and a row another replica has taken over is skipped
rather than run twice (:197-208, RenewClaimAsync doc at :329-333). Execution
itself goes through InternalCommandDispatcher
(.../Processing/InternalCommandDispatcher.cs:21), and the load-bearing detail is that it resolves the
closed ICommandHandler<TCommand, Result> interface: Scrutor's decorators are registered against
the open generic, so what comes back is already wrapped in the feature gate, the authorization check,
logging, cache invalidation, validation, the timeout budget and the transaction. A deferred execution
is therefore the same execution a controller would have got, not a parallel path that re-implements
any of it (:10-20). The rest of the processing namespace is the machinery that loop needs:
IInternalCommandSignal and its
InternalCommandSignal implementation
(.../Processing/InternalCommandSignal.cs:10), a thin wrapper over the same
WakeUpSignal the outbox signal wraps (:5-9, :12);
InternalCommandCycleResult
(.../Processing/InternalCommandCycleResult.cs:17), the record struct that lets a cycle report whether
more due work is waiting and when the oldest not-yet-due row comes due, so the loop smart-waits to
that instant instead of sleeping a full interval (:7-16);
InternalCommandNameResolver
(.../Processing/InternalCommandNameResolver.cs:19), the job-queue counterpart of EventNameResolver
that stores a command under its InternalCommandNameAttribute name when it declares one and under its
assembly-qualified name otherwise, so a rename or a namespace move does not orphan queued rows
(:7-18); and InternalCommandMetrics
(.../Processing/InternalCommandMetrics.cs:17), the one meter (MMCA.Common.InternalCommands, :20)
carrying completions, dead letters, execution latency and observed backlog depth.
One command type can be lifted off the shared loop onto a dedicated lane.
InternalCommandLanes (.../Processing/InternalCommandLanes.cs:10) is the
registry the shared processor reads once, on its first cycle, from a scope
(InternalCommandProcessor.cs:315-325): while it is registered the shared fetch and count exclude its
DedicatedCommandType, and because it is registered only together with that lane, a host without one
polls exactly the pending predicate (InternalCommandLanes.cs:3-8). The lane itself is an
InternalCommandLane record (.../Processing/InternalCommandLane.cs:23) of a
name (the lane metric tag), the stored command type it claims, a configured receiver cooldown, a
receiver-key reader over the deserialized command, a per-batch MaxConcurrency and a
BatchStartBudget (:11-29). InternalCommandLaneProcessor
(.../Processing/InternalCommandLaneProcessor.cs:51) is its drain, a BackgroundService that polls
with the shared pending predicate, order, batch size, grace period and loop, and claims, renews and runs
rows through the row methods of a private, never-started InternalCommandProcessor, so a lane row
executes, retries and dead-letters through the same code as a shared row (:23-26, constructor at
:51-58). Within one claimed batch up to MaxConcurrency rows run at once, each in its own scope and
context; two rows of one receiver never run together; and no row starts once the start budget has
elapsed since the batch's first start, the rows that never started being released uncharged so they are
due again at once (:27-34). A receiver whose real attempt failed cools down on this replica, and while
it does its rows are not sent: each is charged one failed attempt (InternalCommands.ReceiverCoolingDown,
:61) through the unchanged failure path, so it keeps the normal retry timeline and attempt budget, and
the first row whose turn comes after the cooldown runs for real (:35-42). The cooldown actually applied
is clamped by EffectiveCooldown (:103-116) to min(configured, S - attemptTimeout - 1 s), floored at
one second, where S is the shortest possible span from a row's first attempt to its last, so a receiver
that answers from the moment a row is scheduled gets at least one real attempt before that row can
dead-letter (:89-98). That state lives in ReceiverCooldowns
(.../Processing/ReceiverCooldowns.cs:10), an in-memory per-lane, per-replica map that takes no lock
because only the scheduling path reads or writes it (:3-8), and four private nested types carry one
batch: LaneBatch (target, batch context, source name and claim token,
InternalCommandLaneProcessor.cs:693), LaneBatchState (waiting and running rows,
busy receivers, first start and first fault, :705), LaneRow (one claimed row and its
receiver key, :779) and LaneBatchOutcome (progressed, charged and released
counts, :686). The one lane registered today is webhook delivery:
WebhookDeliveryLane keys rows by subscription and
registers the lane registry and its processor only when Webhooks:Enabled and InternalCommands:Enabled
are both true
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookDeliveryLane.cs:36-48, :58-81).
The loop mechanics themselves are not the processor's own code. They live in the Polling namespace,
shared with the outbox drain in Group 04, so both table-draining services
wait, drain and back off identically while every log, metric and activity name stays with the processor
that owns it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Polling/PollingLoop.cs:5-11).
PollingLoop (PollingLoop.cs:12) is a static class with three pieces. RunAsync
(:40-91) waits a 5-second StartupDelay (:18), returns early when the host owns no relational
source, then runs cycles until shutdown: a cycle that reports more ready work re-polls at once, a failed
cycle is reported and treated as one with nothing pending, and every other cycle waits on the wake-up
signal for ComputeWaitTime (:104-122), which is the moment the earliest upcoming row becomes ready
plus the processing delay, capped at the polling interval and floored at one second so an overdue row
cannot hot-loop the processor (:21). DrainAllAsync (:135-171) drains every
TenantDataSourceTarget in order and aggregates the results, and a source
that throws is reported and contributes nothing, so one unreachable database cannot starve the others
(:162-167). ComputeRetryBackoffSeconds (:183-197) is the exponential backoff for a failed row,
base * 2^(attempts - 1) with the exponent clamped at 16, multiplied by a jitter factor in [0.8, 1.2]
before the per-processor cap, so a batch that failed together in one dependency outage does not retry
in lockstep, and a capped backoff stays exactly at the ceiling (:173-178, :188-196). The processor
calls all three (InternalCommandProcessor.cs:76, :106, :127, :633). The wake-up it waits on is
WakeUpSignal (.../Polling/WakeUpSignal.cs:16), a SemaphoreSlim created with a
maximum count of one (:18) whose Signal swallows the SemaphoreFullException a second pending
wake-up raises (:21-31). The cap is the point: each processor drains a whole batch per cycle, so one
pending wake-up is all the information a burst of writes carries, and an uncapped semaphore made N
writes cost N candidate-fetch cycles per relational source that found nothing (:3-15).
The administration namespace is the operational half. InternalCommandsSettings
(.../InternalCommands/Administration/InternalCommandsSettings.cs:15) binds the InternalCommands
section with a default for every property: Enabled defaults to true, the outbox's posture (:27),
a batch of 50 (:31), 5 attempts before dead-lettering, where a Result.Failure counts exactly like a
thrown exception because both mean the work did not happen (:39), a 2-second fallback poll that is only
the backstop for a wake that never arrives (a row another process wrote, a commit path that released no
signal), since even a transaction-scheduled row is woken by the unit of work once its commit succeeds
(:41-50), a processing delay of 0 rather than the outbox's 5, because the queue has no in-process fast
path to race (:52-59), and a 300-second claim lease that must sit comfortably above the longest
expected handler duration and, being renewed before each row runs, bounds one handler rather than the
whole batch (:61-70). A host that sets Enabled=false registers neither the
processor nor the sweep, so InternalCommandsDisabledNoticeService
(.../Administration/InternalCommandsDisabledNoticeService.cs:20) states that once at startup at
Information: a web front end queueing work for a dedicated worker is a legitimate posture and the
wrong thing to discover from an absent background service (:6-18).
InternalCommandCleanupService
(.../Administration/InternalCommandCleanupService.cs:44) purges completed rows past RetentionDays,
because the table stores serialized command payloads that may contain personal data and the pending
index every poll re-scans grows with it, and deletes dead-lettered rows on their own wider window,
logging every such deletion at Warning because it destroys the only record that the work was ever
asked for (:13-28). InternalCommandAdministration
(.../Administration/InternalCommandAdministration.cs:37) is the operator surface over the same
targets, visiting each in its own DI scope (a tenant target only routes correctly once
ITenantContext is set for that scope) and expressing requeue and purge as one set-based statement
per target, because an operator clearing a backlog touches thousands of rows and none of the values
written depend on the row's current state (:15-26). Both background services and the administration
type expand their target list per tenant that keeps its own copy of a source, for the same reason the
audit-trail sweep does: that database has a queue table nothing else would drain.
The tenant boundary, read filter plus write guard
Multi-tenancy (ADR-073) is two
independent halves that meet in this group. The read half is the named Tenant query filter the
base context applies to every non-owned ITenantEntity
(ApplicationDbContext.cs:757-816). Three details make it work: the filter body embeds the context
instance as a constant typed as ApplicationDbContext, so EF rewrites it to the executing context and
lifts CurrentTenantId into a SQL parameter, letting one compiled model serve every tenant
(:502-507, :519-523); the predicate is CurrentTenantId == null || e.TenantId == CurrentTenantId,
so a scope with no tenant (the outbox processor, the seeders, the retention jobs) sees every tenant's
rows (:509-511, :567-571); and the column itself is declared required, 64 characters, non-Unicode, and
indexed on relational engines, because every tenant-scoped read carries it as the leading predicate
(:532-554, width constant at :484). That index follows the filter composition rather than the
column: an entity that is also an IAuditableEntity gets (TenantId, IsDeleted), matching the
AND-composed predicate every read of a soft-deletable tenant row actually carries, and a tenant-only
entity keeps the single-column index (:537-553). The filter reads the value through EF.Property
rather than a CLR member access, so an explicitly implemented interface member or a shadow property
translates identically (:558-565). Because the two filters are named, EF composes them with AND, and
a caller asking for soft-deleted rows drops exactly the SoftDelete filter while the tenant filter
stays in force: the repository contract says so in as many words
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:16-19,
:75-79), and the repository passes that one filter name explicitly
(.../Repositories/EFReadRepository.cs:41).
The write half is TenantSaveChangesInterceptor
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/TenantSaveChangesInterceptor.cs:44).
It stamps the scope's tenant onto an insert that declares none (:116-119), refuses an insert that
names a different one (:122-123), and on update or delete checks both the original and the current
value, so touching another tenant's row and reassigning a row to another tenant are both rejected
(:131-159, with the original reported in preference to the current one at :161-166). An untenanted
insert from an untenanted scope is refused too, because silently writing a row no tenant can ever read
is worse than failing the save (:107-110). Owned types are skipped on both sides: an owned value has
no independent existence and its owner's tenant is already the row's tenant (:69-75). Failures
surface as CrossTenantWriteException
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/CrossTenantWriteException.cs:25),
which derives from InvalidOperationException so existing catch sites treat it like any other save-time
invariant failure (:19-22). The deliberate asymmetry is documented in the interceptor's own remarks: a
caller who bypasses the read filter with EF's parameterless IgnoreQueryFilters() can read across
tenants, but still cannot write across them (:29-33). That is [Rubric §11, Security] and
[Rubric §30, Compliance and Data Governance] in one type. The scope's tenant itself lives in
TenantContext
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/TenantContext.cs:14), which is
set-once-per-scope and idempotent for the same value, and throws rather than switching tenants
mid-scope (:20-44).
What a host declares about tenancy is bound into TenancySettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:47) from the
Tenancy section (:53), and the settings themselves carry the shape of the feature. Enabled gates
resolution, not isolation, so the query filter and the save interceptor are always present and simply
inert while no tenant is resolved, which is why a host that never opts in keeps exactly the behavior it had
(:37-40, default false at :67). RequireTenant defaults to true, so once resolution is on a request
that yields no tenant is rejected with 400 Bad Request rather than reading across every tenant (:91-96).
Both collection properties express their defaults as "empty means the default", read through
EffectiveResolutionOrder (claim, then header) and EffectiveExcludedPathPrefixes (/health, /alive,
/.well-known), because the configuration binder ADDS to a pre-populated collection instead of replacing
it, so a non-empty default would leave a host that configured its own order running the framework's entries
too (:42-48, :56-61, :76-77, :106-107). TenantResolutionStrategy
(:6) names the three sources: Claim is the trustworthy one (the token issuer signed it, so a caller
cannot pick its own tenant), Header is for service-to-service calls behind a trusted gateway, and Host
is defined but not implemented, present only so the configuration contract stays stable (:8-27).
TenancySettingsValidator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:25)
is what makes that honest: registered with ValidateOnStart, it fails the boot when a resolution order
names Host (:54-65) and checks each tenant's overrides against the resolved physical sources when
IDataSourceResolver is registered (:14-18, :39-42), on the reasoning that
every failure here would otherwise surface as silent cross-tenant behavior, which is the exact bug class
tenancy exists to prevent (:8-13). Declaring a tenant is only required for the database-per-tenant case:
a TenantEntrySettings (TenancySettings.cs:135) entry holds per-source overrides
keyed by physical source name, and each
TenantDataSourceOverrideSettings (:138) carries connection
information only, because a tenant database has the same schema as the shared one and the migrations
assembly is deliberately not overridable (:124-137, :140-153). A source without an entry stays shared
and is isolated by the query filter (:126-127).
Database-per-tenant is handled one layer up, in the factory, and background
sweeps expand their work list through TenantDataSourceTargets.Expand
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:52-82),
which emits the shared target for every source plus one extra
TenantDataSourceTarget (:15) per tenant that overrides a source, because
a tenant with its own database is invisible to the shared sweep (:36-40). The sweeps do not each
assemble that list themselves: FrameworkTableTargets
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:32)
is the one answer to "which databases hold the framework's own relational tables on this host", shared
by the outbox and internal-command processors, both cleanup services, both operator surfaces and the
audit-trail sweep (:14-19). Relational() returns every relational source backing a registered
entity, deduplicated and expanded per tenant (:43-44), and its overload adds the source the caller's
own settings name as the table's home when that engine is relational (:54-60). It is recomputed per
call, so late-loading module assemblies are seen, and Cosmos sources are skipped because they host none
of those tables (:21-22).
Recording what changed, the audit trail
AuditTrailSaveChangesInterceptor
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:83)
is the fourth interceptor (ADR-075).
It records a field-level history for entities marked
IAuditedEntity, writing
AuditTrailEntry rows in the same transaction as the change they describe, on the
outbox precedent that a trail committable without its data is worse than no trail (:24-27). A
Modified save produces one row per property whose value actually changed; Added and Deleted
produce a single summary row with a null PropertyName
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailEntry.cs:17-23,
class at :23). An owner left Unchanged whose owned value object changed is recorded too, through
the same OwnedDependents check the audit interceptor uses
(AuditTrailSaveChangesInterceptor.cs:272-279, the Unchanged arm at :259), with the owned property
named navigation.property (:418). Four things are worth knowing about it. It is opt-in twice over,
once through AddAuditTrail (the interceptor is resolved with GetService) and once through
AuditTrail:Enabled (which maps the table), and both are checked cheaply per save by asking the model
whether the entity type exists at all (:38-40, model check at :206). Both switches read the same bound
AuditTrailSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSettings.cs:16,
section name at :19), whose Enabled decides both whether changes are recorded and whether the
AuditTrailEntries table is mapped at all, defaulting to false so adopting the framework never adds a
table or a write per change to a host that did not ask for one (:10-15, :21-26), whose RetentionDays
defaults to 90 and is inert unless the host also runs the scheduler (:28-38), and whose DataSource
names the one engine the v1 read surface queries, defaulting to SQL Server because the table is relational
(:40-46). Personal data never reaches the table: a property carrying
PiiAttribute records
PiiRedactor.RedactedToken on both sides, and the
redaction happens at capture, not at read, so the trail cannot become a second copy of a data
subject's personal data that erasure would have to chase (:43-46, applied at :347-348 and for owned
values at :419-420,
ADR-005). The same token replaces
credentials and ciphertext with no marker needed: the password hash and salt of an entity implementing
IAuthUser, found through the interface map, any property carrying
SensitiveAttribute (:49-53), and any
property mapped through EncryptedStringConverter, which reaches the
interceptor as decrypted plaintext (:56-58). The framework's own
bookkeeping types are excluded by CLR type rather than by marker absence, which is what stops the trail
from recording its own rows in an unbounded feedback loop (FrameworkEntityTypes at :137, checked at
:195 from ShouldAudit at :252). And the
correlation value it records is the ambient Activity trace id rather than a scoped correlation
service, because a singleton interceptor holding a context built by the singleton physical factory
cannot reach a scoped service without a lifetime bug; the doc comment says exactly that and names the
accessor pattern tenancy introduced as the way to change it later (:61-70). The values every row of
one save shares (user, instant, trace id, tenant) are gathered once into a
CaptureContext record struct (created at :230, declared at :874), and a row
describing an insert whose key the database has not assigned yet is parked as a
PendingEntityKey (:883) until the store-generated key exists (created at
:320, collected at :244-252 into a per-context weak table declared at :119, read back after the
save at :550 and :570). After the insert each pending row is resolved into a
KeyFix record (:888, built at :618-628), the row plus its now-known key, and the fixes
are written set-based: one ExecuteUpdate per batch of up to KeyFixUpBatchSize (256, :113) rows
whose value is a CASE on the row id, so a bulk insert of N identity-keyed rows costs N / 256
statements rather than N. The fix-up bypasses the change tracker, runs inside the save's transaction so
the trail row and its key commit together, and clears its capture marker only once it succeeded
(:533-547, batching at :552-561 and :572-580).
Every free-text value a row carries (entity type, key, property name, trace id, tenant) is cut to its
column width through ColumnWidth.Truncate
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/ColumnWidth.cs:4, body at
:10-11), an internal helper that truncates and preserves null (AuditTrailSaveChangesInterceptor.cs:233-234,
:277, :346, :418, :628); the internal-command processor and the scheduled-job runner reuse it for their
error columns (InternalCommandProcessor.cs:549, :573).
Two more types close the feature: AuditTrailReader
(.../AuditTrail/AuditTrailReader.cs:34) serves paged history for one entity behind
IAuditTrailReader and states its own v1 limitation,
that it reads only the Default source's trail table (:16-23), and
AuditTrailCleanupJob (.../AuditTrail/AuditTrailCleanupJob.cs:45) is the
framework's own recurring IScheduledJob, purging rows past
RetentionDays (cutoff at :70) nightly at 03:00 UTC (:60) from every relational source
FrameworkTableTargets.Relational() returns, a list already expanded per
tenant so a tenant with its own database gets swept too (:72). The delete itself is
BatchedDelete
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Retention/BatchedDelete.cs:15, called
at AuditTrailCleanupJob.cs:119), the one paging helper every retention sweep shares: it reads up to
1000 ids (BatchSize, :18) in the sweep's order and deletes them by id with ExecuteDelete,
repeating until a short page (:103-127), because an IN list translates on every relational engine
where a limited DELETE does not, and a first sweep over a neglected table becomes many short statements
instead of one long lock (:8-14). The key must be a single Guid column, as on every framework
bookkeeping table (:61-62); cancellation is observed between batches, and the rows actually removed
are reported exactly once even when a batch throws (:20-36, :54-57); and an IAuditableEntity is
refused outright, because those rows are deleted by setting IsDeleted and erasing one would drop it
from audit, restore and erasure accounting (:64-68, :84-88). The internal-command, refresh-session,
outbox and inbox sweeps call it too (InternalCommandCleanupService.cs:110, :151,
RefreshSessionCleanupService.cs:127, .../Outbox/Administration/OutboxCleanupService.cs:104, :168,
:189). The audit-trail job only runs if the host also runs the
scheduler, and a host that records the trail without one is fully supported: pruning is then the
operator's job (:23-26).
Repositories, specifications, and the unit of work
Handlers do not touch a DbContext directly. They ask a UnitOfWork
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:20) for a repository.
The repository contract is deliberately interface-segregated
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs, the contract
ADR-055 states): a
handler that only needs a lookup can depend on the narrow
IEntityReader<TEntity, TIdentifierType> (IRepository.cs:21)
or IEntityQuerier<TEntity, TIdentifierType> (:80);
IReadRepository<TEntity, TIdentifierType> (:332) combines
both plus four IQueryable surfaces (tracking, no-tracking, single-query, split-query, :336-345),
IWriteRepository<TEntity, TIdentifierType> (:385) adds
mutation, and IRepository<TEntity, TIdentifierType> (:508) is
the union. That layering is the group's clearest [Rubric §1, SOLID] (interface-segregation) statement.
The concrete
EFReadRepository<TEntity, TIdentifierType>
(.../Repositories/EFReadRepository.cs:21) and
EFRepository<TEntity, TIdentifierType>
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:27) wrap
an EF DbSet; the read side keeps its GROUP BY projections in the private
GroupedCount<TKey> and GroupedSum<TKey> records
(EFReadRepository.cs:185, :190) so the aggregation happens in the database rather than in memory.
Its lookup read (GetAllForLookupAsync, EFReadRepository.cs:223) follows the same rule for a
non-string display property: a string property projects straight onto
BaseLookup<TIdentifierType>, while any
other type projects onto LookupRow<TId, TName> (EFReadRepository.cs:735),
the id plus the raw name value in its own CLR type (:343-362), because EF can translate that
projection for any mapped property but cannot translate a ToString() on a value object
(:712-716). The rows are ordered and capped server-side at
EntityQueryPipeline.MaxUnboundedResultLimit
(1000, MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:25, defined as KeysetPageRequest.MaxPageSize at MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:27)
and formatted to display strings only after materialization (:280-297). The compiled selectors are
cached by the property's canonical name and capped at 512 entries (:30, :313-341), so the
case permutations of one column name sent to an anonymous endpoint cannot mint unbounded cache entries
(:305-311).
The write side patches already-tracked entities in place through an O(1)
Local.FindEntry lookup instead of re-attaching (EFRepository.cs:56-68) and seeds RowVersion
original values for optimistic concurrency on both the aggregate and any child implementing
IRowVersioned (:75-93,
ADR-035). Two set-based escape
hatches sit beside the tracked path: ExecuteDeleteAsync, which the interface itself documents as
bypassing domain events, audit stamps, and soft-delete (IRepository.cs:464), and
ExecuteUpdateAsync (:480), the contention-proof conditional update whose guard predicate lets
the database arbitrate two racing callers with no rowversion retry loop. The latter is described
through the persistence-agnostic
IUpdatePropertySetter<TEntity> surface and replayed onto EF's setters
builder by UpdatePropertySetterBuilder<TEntity>
(.../Repositories/UpdatePropertySetterBuilder.cs:14), which is what keeps EF Core out of the
Application layer, and because ExecuteUpdate bypasses the interceptor pipeline the repository stamps
LastModifiedOn/By itself unless the caller assigned them (EFRepository.cs:115-129).
The read repository does not compose queries by hand. SpecificationEvaluator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/SpecificationEvaluator.cs:21)
turns an ISpecification<TEntity, TIdentifierType>
into an IQueryable: criteria always, then the includes, the
OrderExpression chain, and the paging a
QuerySpecification<TEntity, TIdentifierType>
carries (:40-68), with the shape deliberately skipped for aggregate reads because joining includes to
count rows costs a join per navigation (:30-34). Tracking and soft-delete scope are not its
business: those choose the base queryable, which only the repository can do (:15-19). It also owns the
one split-query heuristic in the framework, opting into AsSplitQuery as soon as any include targets a
collection navigation (:93-101), and EFReadRepository.ApplyIncludes delegates to it so the
string-include path and the specification path cannot drift (:78-79,
EFReadRepository.cs:562-565). Cursor paging is the sibling helper:
KeysetQueryBuilder (.../Repositories/KeysetQueryBuilder.cs:22) resolves the
requested sort property or fails validation (:35), orders by (sortKey, Id) with the identifier
tie-break that makes the order total (:50-51), and builds the composite seek predicate against the
last row of the previous page (BuildSeekPredicate at :118), so GetPageByCursorAsync
(IRepository.cs:318, implemented at EFReadRepository.cs:632) seeks straight to the boundary instead
of counting past every skipped row. Exactly one sort key is supported, by design
(KeysetQueryBuilder.cs:17-20). That is [Rubric §12, Performance and Scalability] expressed as a
contract rather than as advice.
Two factories keep the wiring honest. RepositoryFactory
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:15)
builds a repository over a given context and conditionally wraps it in a MiniProfiler decorator
(EFRepositoryDecorator<TEntity, TIdentifierType> or
EFReadRepositoryDecorator<TEntity, TIdentifierType>)
when UseMiniProfiler is on (:34-38, :58-62), adding timing without the base repository knowing,
and it activates both through a cached compiled ObjectFactory rather than reflecting on every call
(:70-84). DbContextFactory
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:49)
is the scoped coordinator: it caches one ApplicationDbContext per
DataSourceKey so every repository in a scope shares one change tracker (:99-133),
gives each new context live scope accessors rather than copied values (:115, doc at :135-141), and enlists a
late-created context into an already-open transaction (:117-120). It is also the database-per-tenant
routing point: when the scope's tenant overrides a source, the context is created against that tenant's
connection string while keeping the original DataSourceKey, which is what lets one compiled model
serve every tenant's database (ResolveTenantOverride, :163-169), and a cached routed context is refused to a second tenant
rather than silently serving the first tenant's rows (:124-125, guard at :202-219), just as a shared
context created before the tenant resolved is refused to a tenant that overrides that source
(:127-129, :227-230). Its save loop runs up to
MaxSavePasses (3, :64) passes over the cached contexts, because dispatching events in-process can
materialize a context for a source nobody had touched yet (:279-297), and it closes with a hard
assertion: any context still reporting ChangeTracker.HasChanges() when the unit of work returns throws
rather than silently discarding those changes (:299-316).
Because there can be more than one physical source in play, ExecuteInTransactionAsync (:551)
runs the operation under the first transactional context's execution strategy, opens a transaction per
source, and commits them sequentially with no two-phase commit (TryCommit at :719);
cross-source consistency is the outbox's job, and the doc comment is explicit that a commit failure on
the second source leaves the first one committed (:540-549). The method is re-entrant: a nested call
joins the ambient transaction instead of opening a second one, so only the outermost call may begin,
commit, roll back, or flush (:555-563). A returned failed
Result rolls back exactly like an exception (:615-622),
which is what makes ADR-013's
Result-over-exceptions rule safe for partial persistence; rollback also drops the deferred event
dispatch (:617-620), the deferred flush runs only after every commit has succeeded (:636-643), and a
retry resets the change tracker first so the aborted attempt's Added entities are not inserted twice
(ResetForRetry at :836, called at :581). Before committing, the unit also refuses to discard
work: anything still tracked but unsaved throws, except an internal-command row that was only
enrolled on the context while the transaction was open, which is saved inside the transaction so it
commits with the change that scheduled it (FlushEnrolledCommandsBeforeCommitAsync, :671-707, called
at :625). Once every commit has succeeded it releases the processor wakes those enrolled rows owe
through EnrolledCommandWake, before the deferred event flush so a throwing
in-process handler cannot swallow them (:631-634), and DropDeferredWork forgets both the deferred
dispatch and the owed wake on rollback or retry (:850-854). DbContextFactory further carries the engine-neutral half of the explicit-key insert
(RequestExplicitKeyInsert at :322, SaveWithExplicitKeyInsertAsync at :330): when one is requested
and the context's engine has an IExplicitKeyInsertDialect, the save is
split into one ExplicitKeyInsertGroup round per table with the toggle on
(:264-270, :293-294), for importing entities with explicit database-generated ids. The rounds
run principals first: ExplicitKeyInsertRoundOrder
(.../Factory/ExplicitKeyInsertRoundOrder.cs:17) derives the order from the EF model's foreign keys
rather than from the order entities were added to the change tracker, because each round hides every
other round's added rows, so EF's own per-command ordering cannot help across rounds and a dependent
table written first would fail its foreign key (:6-15, applied at DbContextFactory.cs:342-346). Its
Order is Kahn's algorithm over the table dependency graph: lowest ready index first so independent
rounds keep their original order, a self-reference is no edge because EF orders rows within one round
itself, and a cycle is broken deterministically at the lowest remaining index
(ExplicitKeyInsertRoundOrder.cs:19-34, :70-99). The factory also pins one connection for the whole
sequence, because the toggle is session state and EF would otherwise hand the connection back to the
pool between commands (DbContextFactory.cs:351-361). It also runs the
MigrateAsync / HasPendingMigrationsAsync sweeps (:784, :820) over every source whose resolved
PhysicalDataSource.IsMigrationTarget holds: the source UsesMigrations under
its engine's MigrationPolicy, and it is not an optional source left without a
connection string (PhysicalDataSource.cs:42-60, target selection at DbContextFactory.cs:844-857).
UnitOfWork sits on top, resolving an entity's physical source through
IDataSourceService, handing the matching context to the factory, and caching the
resulting repository per closed generic interface type (UnitOfWork.cs:48-81). The physical creation
itself runs through PhysicalDbContextFactory
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/PhysicalDbContextFactory.cs:19),
a singleton that hands construction to the key's engine through IDataSourceEngine.CreateDbContext (:32) and whose
doc comment warns it must never be pooled, because each instance carries per-source constructor
state that pooling would smear across databases (:13-17). The interfaces
(IUnitOfWork, IDbContextFactory,
IPhysicalDbContextFactory, IRepositoryFactory)
keep the application layer talking to abstractions. Every member of that factory family has its own
section below, including the type that exists only because of what the coordinator does,
TransactionCommitAmbiguousException
(.../Factory/TransactionCommitAmbiguousException.cs:22), which the commit path raises when the commit
itself fails with an outcome nobody can vouch for, naming each physical source's outcome (committed,
ambiguous, or rolled back) so the partial state is observable rather than inferred (:57-70,
DbContextFactory.cs:755-782). That exception is thrown outside the execution strategy on purpose
(DbContextFactory.cs:620-621), because the strategy walks an exception's whole inner chain to decide
retriability and would otherwise re-run the operation on top of a possibly-durable commit.
Routing an entity to its database
The heart of ADR-006 is that every
entity resolves to a DataSourceKey
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/DataSourceKey.cs:15), a
(Engine, Name) record struct where the DataSource engine
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IDataSourceService.cs:6) is
one of Cosmos DB, SQLite, SQL Server, or PostgreSQL, and Name is a physical database name defaulting to
"Default" (DataSourceKey.cs:18-23). Two layers compute this.
DataSourceResolver
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceResolver.cs:16),
the IDataSourceResolver singleton (.../DataSources/IDataSourceResolver.cs:15),
builds the logical-to-physical map once per engine from configuration and hands out the resolved
PhysicalDataSource (BuildEngineMap at :195, ResolveLogical at :93, GetPhysical at :183). Named sources with no connection
string, or whose connection identity equals the top-level one, collapse onto the Default source,
so a host with no DataSources section behaves exactly like a single-database monolith
(DataSourceResolver.cs:315-365), and sources sharing a connection identity collapse onto one canonical
key named after their alphabetically-first member (:380-411, canonical name at :386). What the
Default source is built from is itself resolved rather than assumed: the top-level
ConnectionStrings section first, and when it names nothing for this engine while DataSources names
exactly one database on it, that database becomes Default, which is what keeps the framework's own
tables working in a host that declares its database only under DataSources (:219-285, captured in
the private DefaultSeed record at :217). Identity is the connection string compared
ordinally, with the database name appended on an engine whose ConnectionIdentityIncludesDatabaseName
is set (Cosmos, because one account hosts many databases, :496).
The resolver fails fast when two logical names collapsing to one database declare conflicting
migrations assemblies (:464-480) and logs a warning when a separate source on an Always
MigrationPolicy engine (SQL Server) falls back to
the Default migrations assembly (:401, message at :509). It also substitutes the host's own
engine for a request naming an engine the host does not configure, in a fixed relational-first
preference order ranked by each engine's SubstitutionPriority (:35-36, applied through
SubstituteUnconfiguredEngine at :128), because every table the framework owns is relational and honoring
an unconfigured engine literally handed those components an empty connection string.
What the resolver reads is two bound settings objects.
ConnectionStringSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/ConnectionStringSettings.cs:12)
is the top-level ConnectionStrings section (:15): one connection string per engine plus the SQL Server and
PostgreSQL migrations assemblies, and deliberately no required property, because a host may run entirely on SQLite
or Cosmos, or declare its databases only under DataSources (:5-10, :17-33).
DataSourcesSettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourcesSettings.cs:13)
is the named half, a dictionary keyed by logical source name (:16, :23-25) that AddInfrastructure
builds directly from configuration rather than through the options pipeline, because a root-level
dictionary section does not bind there (:8-11); it rejects an empty entry name and reserves Default,
which is configured through the top-level section instead (:27-39). Each entry is a
DataSourceEntrySettings
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceEntrySettings.cs:19)
whose properties are all optional and fall back to the corresponding top-level value, which is exactly the
collapse-onto-Default behavior the resolver implements (:3-8). The one property with no top-level
fallback is SqliteMigrationsAssembly: ConnectionStrings carries SQL Server and PostgreSQL
migrations assemblies but no SQLite one, so a SQLite Default source declares its own through a collapsing
entry, and a mixed-engine host cannot silently apply its SQL Server migrations assembly to a SQLite
database (:42-55). Across both
sections one rule is enforced at startup by
ConnectionStringSettingsValidator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/ConnectionStringSettingsValidator.cs:30),
registered with ValidateOnStart: the host must be able to reach at least one database, top level or
named, or it fails to boot with a message naming both configuration shapes (:38-43, :46-59). That rule
replaced a [Required] annotation on the SQL Server connection string, which encoded "SQL Server is the
only engine a host can boot on" and failed a SQLite-only host whose every entity resolved to a configured
database (:10-24).
EntityDataSourceRegistry
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/EntityDataSourceRegistry.cs:21),
also a singleton, scans the configuration assemblies and maps each entity to its physical key, deriving
the engine from the UseDataSourceAttribute
on the configuration class and the logical name from
UseDatabaseAttribute, the entity's module
namespace via NamespaceConventions.GetModuleName, or Default
(EntityDataSourceRegistry.cs:159-172). It caches an immutable Snapshot of frozen
collections built on first access (:25-28, :82-92, built at :115-160), rescans once on a lookup
miss when the assembly set changed so late-loaded module assemblies are picked up (:95-113), rejects an
entity claimed by two different sources (:141-149), and precomputes the distinct physical sources in
use so the outbox processor's per-poll call allocates nothing (:75-80, :157-159). Because the
registry reads the same attributes the model configuration reads, routing and model contents agree by
construction, and configurations that implement a provider interface directly without the attributed
base classes are deliberately skipped as legacy (:163-176). DataSourceService
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceService.cs:12) is the thin
application-facing facade over IEntityDataSourceRegistry, and it answers
the one question navigation loading needs: two entities support EF .Include() only when their physical
keys are equal and the engine is relational (DataSourceService.cs:32).
NavigationPopulatorStartupValidator
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:36)
turns that answer into a boot check (ADR-002).
It is an IHostedService that classifies every [Navigation] of every entity this host maps exactly as
the query path does, and for each navigation EF cannot include (the two entities live in different
databases, the engine has no relational includes, or the target is not mapped here) asks the registered
populator whether it handles it; any navigation left uncovered fails StartAsync with an
InvalidOperationException naming each one, instead of letting every read with includes return it empty
(:11-23, :46-59). A host whose navigations all share one relational database has nothing unsupported,
so the check costs one reflection pass, and AddInfrastructure registers it with TryAddEnumerable so
several modules run it once (:25-29).
One registry answers every engine question
Four engines would otherwise mean a four-way switch in every component that maps a key, quotes a
column, picks a migrations assembly or decides whether a source has an outbox. The framework keeps
exactly one place that knows engines apart. IDataSourceEngine
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/IDataSourceEngine.cs:18)
is the internal contract, and its doc comment states the goal: no call site branches on
DataSource (:9-16). Its members fall into three groups. The descriptive ones say how
the engine is configured: its rank when the resolver substitutes it for an unconfigured engine (:29),
the open generic entity-configuration interface whose implementations belong to its model (:32), the
setting that names its migrations assembly (:38), whether connection identity includes the database
name (:44), and how to read its connection string and migrations assembly from the top-level section,
a named entry or a tenant override (:49-69). The capabilities are one value (:74). The behavior hooks
are the few places the engine has to act rather than answer: build its sealed context over one physical
source, never pooled (:83-86), apply its table or container mapping and key generation to one entity
(:95-97), add covering index columns (:103), quote a column and build the soft-delete index
predicate (:108-113), and expose an explicit-key insert dialect, or none (:119).
DataSourceEngines (.../Engines/DataSourceEngines.cs:19) is the registry: a
static class holding the four engines (:22-28) in a frozen dictionary keyed by the shipped
DataSource value (:30-31), whose For throws on an unregistered value (:40-43). It is static
rather than a DI service on purpose: several consumers run where no container is reachable (the
model-building conventions, EntityTypeConfiguration.ApplyEngineConventions, SoftDeleteFilterSql,
IndexBuilderExtensions), and the engines are stateless facts about a closed enum only Common can
extend, so a DI extension point would buy no extensibility; adding a fifth engine is one class plus one
line (:6-18). The four implementations are
SQLServerDataSourceEngine (.../Engines/SQLServerDataSourceEngine.cs:19),
PostgreSQLDataSourceEngine (.../Engines/PostgreSQLDataSourceEngine.cs:17),
SqliteDataSourceEngine (.../Engines/SqliteDataSourceEngine.cs:16) and
CosmosDataSourceEngine (.../Engines/CosmosDataSourceEngine.cs:18), with
substitution priorities 0, 1, 2 and 3 (SQLServerDataSourceEngine.cs:29,
PostgreSQLDataSourceEngine.cs:27, SqliteDataSourceEngine.cs:26, CosmosDataSourceEngine.cs:28),
which is the relational-first order the resolver substitutes in.
What differs between engines is a DataSourceEngineCapabilities record
(.../Engines/DataSourceEngineCapabilities.cs:23) of five values (:24-28). Only facts whose values
genuinely differ get a member, and everything that splits the engines exactly along the relational line
is the single IsRelational flag: same-source .Include(), transactions, raw parameterized SQL,
indexes, foreign keys whose delete behavior matters, Any(predicate) translation and the framework's
own relational tables (:3-20). That one flag is what the outbox capture, the transaction coordinator,
the conventions and the .Include() check read (DomainEventSaveChangesInterceptor.cs:277,
DbContextFactory.cs:900-901, SoftDeleteUniqueIndexConvention.cs:43, DataSourceService.cs:32).
MigrationPolicy (.../Engines/MigrationPolicy.cs:8) decides whether a source is
migrated or created outright: Never for Cosmos, WhenAssemblyConfigured for SQLite and PostgreSQL,
and Always for SQL Server, where a named source with no assembly falls back to the Default source's
with a warning (:10-20; values at SQLServerDataSourceEngine.cs:42, PostgreSQLDataSourceEngine.cs:40,
SqliteDataSourceEngine.cs:39, CosmosDataSourceEngine.cs:42).
RowVersionStrategy (.../Engines/RowVersionStrategy.cs:8) decides the
concurrency token: None on Cosmos, StoreGenerated (a rowversion, never stamped) on SQL Server, and
ClientStamped on PostgreSQL and SQLite, where the audit interceptor writes it (:10-17).
ConnectionStringRequired is true only for SQL Server, so a SQL Server source with no connection string
is a startup failure rather than an optional source to skip (DataSourceEngineCapabilities.cs:10-13,
SQLServerDataSourceEngine.cs:43), and NullsSortFirstAscending is false only for PostgreSQL, which
keyset pagination has to know (DataSourceEngineCapabilities.cs:21, PostgreSQLDataSourceEngine.cs:43).
The explicit-key insert shows the split between engine-specific and engine-neutral work most clearly.
IExplicitKeyInsertDialect (.../Engines/IExplicitKeyInsertDialect.cs:13)
is the engine half, and only an engine that refuses an explicit value for a store-generated key without a
session toggle has one: SQL Server, whose engine class implements the dialect itself
(SQLServerDataSourceEngine.cs:19, :49) and emits SET IDENTITY_INSERT [schema].[table] ON or OFF
(:163). Every other engine returns null and the save runs unchanged
(PostgreSQLDataSourceEngine.cs:47, SqliteDataSourceEngine.cs:46, CosmosDataSourceEngine.cs:49). The
dialect finds the added entries carrying explicit store-generated keys, grouped by table
(IExplicitKeyInsertDialect.cs:21), each group an ExplicitKeyInsertGroup
record of schema, table and entries (.../Engines/ExplicitKeyInsertGroup.cs:12), and builds the toggle
statement (IExplicitKeyInsertDialect.cs:28); grouping the rounds, hiding other tables' entries,
excluding their domain events and pinning the connection stay in DbContextFactory
(:5-12). Every engine type is internal, so a consumer never sees one: the public surface is still the
DataSource value on an attribute, and this registry is what turns that value into behavior.
Three model-finalizing conventions and the identifier mapping
The base context adds all three of its conventions in ConfigureConventions
(ApplicationDbContext.cs:605-627), and each exists because a cross-cutting policy above would
otherwise produce an invalid or surprising model.
CrossDataSourceDegradeConvention
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/CrossDataSourceDegradeConvention.cs:34,
added at ApplicationDbContext.cs:614) is what lets routing be lazy and attribute-driven and still
produce a valid EF model. When a relationship's two ends live in different physical sources it removes
the foreign key (a database cannot enforce an FK into another database), keeps the declared scalar FK
columns plus a compensating index unless an existing index already covers them as a prefix, ignores the
CLR navigation members, and drops the foreign entity types out of this database's model entirely
(CrossDataSourceDegradeConvention.cs:39-90, :110-140). It works through EF's mutable model API
rather than convention builders, because the soft-delete and concurrency helpers have already promoted
every entity type to the Explicit configuration source (:22-24, :44-46), it eagerly drops the
convention-created FK index before the coverage check so the column does not end up unindexed
(:126-131), and it skips the compensating index on Cosmos, which auto-indexes everything and rejects
explicit index definitions, which the convention reads as the engine's IsRelational capability (:66). Runtime navigation across sources then flows through the
INavigationPopulator<in TEntity>
batch-loading machinery in Group 11. Crucially, when every entity
collapses onto one physical source (the monolith case) nothing is foreign and the convention returns
early (:52-55), so the model is identical to the single-database model. That is the property that lets
the same codebase run as a monolith today and as split services later without a rewrite, the core
[Rubric §7, Microservices Readiness] claim.
SoftDeleteUniqueIndexConvention
(.../Conventions/SoftDeleteUniqueIndexConvention.cs:34, added at ApplicationDbContext.cs:620) closes
a smaller but sharper hole. Soft-delete hides a row from queries, but a plain unique index still enforces
uniqueness against it, so "deleting" a speaker would permanently block re-creating one with the same
email. The convention adds an IsDeleted = 0 filter to every unique index on a soft-deletable entity
and extends rather than skips a hand-authored filter, appending its clause with AND so an index
already narrowed on something else keeps its own predicate and still stops enforcing uniqueness against
soft-deleted rows; a filter that already constrains the soft-delete column is left exactly as it is, so
the append is idempotent (SoftDeleteUniqueIndexConvention.cs:36-81). It is a no-op for Cosmos
(:43, any non-relational engine). The predicate text itself is not built inline: both this convention and the opt-in
HasSoftDeleteFilter extension go through SoftDeleteFilterSql.Build
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SoftDeleteFilterSql.cs:18, Build at :35), which
reads the column name from the model and asks the engine for the predicate and the quoting
(IDataSourceEngine.BuildSoftDeleteFilter and QuoteColumn, :35, :70; null where filtered indexes are unsupported, which is Cosmos), with a normalized comparison for the already-present check (:57-58), so the
automatic and the hand-authored path can never disagree.
IndexBuilderExtensions (.../Configuration/IndexBuilderExtensions.cs:10) is
that opt-in half, an extension(IndexBuilder) block for the case the convention deliberately leaves
alone: a hand-authored non-unique index that serves a live-row query and wants the same predicate
(:12-65, with an optional additional predicate joined by AND at :60-64). Both conventions run at
model finalization, after module configurations have declared their indexes and after EF's own
relationship discovery, which is why they can see the finished picture.
The third convention is RestrictDeleteByDefaultConvention
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/RestrictDeleteByDefaultConvention.cs:42,
added last of the three at ApplicationDbContext.cs:627 so it never stamps a relationship the
cross-source convention has already removed,
ADR-119). EF's own default
is the opposite posture: a required relationship cascades, so deleting a parent silently deletes its
children in the database, below the aggregate's invariants, below the soft-delete filter and below the
domain events the framework raises. Restricting by default inverts that, so a delete that would orphan
rows fails loudly and a genuine cascade becomes a decision recorded with
.OnDelete(DeleteBehavior.Cascade) in the entity configuration (:9-19). Two things are left alone:
an ownership foreign key keeps its cascade, because an owned type has no identity apart from its owner
and EF requires it, and any behavior anybody configured (fluent OnDelete or the [DeleteBehavior]
attribute) is kept exactly as configured. Both are stamped rather than changed: every foreign key
carries a MMCA:DeleteBehaviorSource annotation naming which of the three sources decided it, so a
finalized model can be audited without re-running the convention, and DeleteBehaviorConventionTestsBase
reads exactly that annotation to assert every cascading relationship was opted into on purpose
(:21-31). Like its siblings it is a no-op for Cosmos, which has no foreign key constraints to
restrict and where stamping a decision the provider cannot enforce would only make the audit lie
(:33-37, checked at :66).
ConfigureConventions ends with the one piece that is not a convention at all:
StronglyTypedIdModelConfiguration.Apply
(.../Persistence/Conventions/StronglyTypedIdModelConfiguration.cs:21, called at
ApplicationDbContext.cs:629-637,
ADR-115). A host
that calls AddStronglyTypedIds registers a StronglyTypedIdRegistry, and this declares one
pre-convention type mapping per declared identifier, so every property of that type maps to the
primitive it wraps: keys, cross-module scalar references, owned-type members and framework-table
columns alike, on SQL Server, PostgreSQL, SQLite and Cosmos, because it runs on the one base context
(:7-20). Absent the registry it is a no-op, which is the default posture: the primitive identifier
aliases stay the identifier model and no existing entity changes
(ApplicationDbContext.cs:629-637). Pre-convention is the load-bearing word. The actual conversion is
StronglyTypedIdValueConverter<TSelf, TValue>
(.../Persistence/Conversions/StronglyTypedIdValueConverter.cs:33), with
StronglyTypedIdValueComparer<TSelf> (:57) beside it; the same
converter serves an optional identifier, because EF lifts a non-nullable struct converter over
Nullable<T> itself, so there is no nullable counterpart (:21-25). A converter attached at model finalization would arrive after the provider's value-generation
conventions had already inspected the property, so a wrapped int key would silently lose its
IDENTITY strategy. Declared pre-convention, the provider CLR type is known before any of that runs,
the column stays the same int, bigint, uniqueidentifier or nvarchar it was, and adopting a
wrapper is therefore neither a schema change nor a migration (StronglyTypedIdValueConverter.cs:7-19).
Entity configuration and engine portability
Concrete entity configurations derive from the engine-aware
EntityTypeConfiguration<TEntity, TIdentifierType>
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfiguration.cs:27)
or, more commonly, one of the fixed-engine shims like
EntityTypeConfigurationSQLServer<TEntity, TIdentifierType>
(.../EntityTypeConfigurationSQLServer.cs:17), which is that base annotated
[UseDataSource(DataSource.SQLServer)] (:16), with
EntityTypeConfigurationSqlite<TEntity, TIdentifierType>
(.../EntityTypeConfigurationSqlite.cs:17) and
EntityTypeConfigurationCosmos<TEntity, TIdentifierType>
(.../EntityTypeConfigurationCosmos.cs:18) and
EntityTypeConfigurationPostgreSQL<TEntity, TIdentifierType>
(.../EntityTypeConfigurationPostgreSQL.cs:22) as its three siblings. The base reads the attribute off its own
runtime type and throws a clear error when it is missing (EntityTypeConfiguration.cs:43-46), then
applies the engine's conventions in ApplyEngineConventions (:69-77), which hands the mapping to the
engine's ApplyKeyAndTableMapping hook (:77): SQL Server gets a table in a
module schema (SQLServerDataSourceEngine.cs:94-103), SQLite a plain table, and Cosmos a per-module container with the
entity id as partition key (CosmosDataSourceEngine.cs:107-113), each mapping key generation according to the entity's
EntityTypeExtensions.IsIdValueGenerated
marker (SQLServerDataSourceEngine.cs:103-104): ValueGeneratedOnAdd for database identity and
ValueGeneratedNever otherwise. Cosmos has no server-side identity and a client-side counter cannot be
unique across instances or across a restart, so the Cosmos engine refuses an entity marked
[IdValueGenerated] at model build with an InvalidOperationException rather than hand out colliding
ids at run time, and always maps the key ValueGeneratedNever: a Cosmos entity assigns its own id
(CosmosDataSourceEngine.cs:86-89, check at :98-105, key at :113). Because the engine is a single attribute and
the base implements all four provider marker interfaces
(IEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>,
IEntityTypeConfigurationSqlite<TEntity, TIdentifierType>,
IEntityTypeConfigurationCosmos<TEntity, TIdentifierType>,
IEntityTypeConfigurationPostgreSQL<TEntity, TIdentifierType>
(.../EntityTypeConfiguration/IEntityTypeConfigurationPostgreSQL.cs:13),
all over the common
IEntityTypeConfigurationBase<TEntity, TIdentifierType>),
moving an entity between engines is a one-line attribute change with no configuration-body edits
(EntityTypeConfiguration.cs:9-23). The shared
EntityTypeConfigurationBase<TEntity, TIdentifierType>
(.../EntityTypeConfigurationBase.cs:19) handles the one universal concern: excluding the in-memory
DomainEvents collection from mapping (:25-32). Value objects reach the database through this layer
too: EntityTypeBuilderExtensions
(.../Configuration/EntityTypeBuilderExtensions.cs:13) flattens a
Money into an amount plus a three-character non-Unicode
ISO 4217 code column with a read-leg fallback to the zero-Money sentinel
Currency (:26, mapping at :63-94, fallback at
:84), and its OwnsAddress sibling flattens an Address into six columns on the owner's table with
the lengths and required-ness the framework's consumers already configured by hand (:96-99, method at
:131); the two converters in .../Conversions/EmailValueConverter.cs map
Email to a plain string in required
(EmailValueConverter at :33) and optional
(NullableEmailValueConverter at :60) flavors; and
EnumerationValueConverter<TEnumeration>
(.../Conversions/EnumerationValueConverter.cs:38) stores a smart enumeration as its plain int
value, so replacing a CLR enum property with an enumeration is not a schema change (:6-11). The same
converter serves an optional property, since EF never hands a null to a converter that does not
convert nulls; an optional one is mapped through the non-generic HasConversion overload (:19-25).
EnumerationNameValueConverter<TEnumeration>
(EnumerationValueConverter.cs:77) is the opt-in alternative that stores the member's Name instead,
read back through
Enumeration<TEnumeration>.FromName,
which matches case-insensitively (:52-74, legs at :85-88). Both read legs share one contract: a
stored value no member declares throws an InvalidOperationException naming the type and the value
through UnknownStoredValue
(.../Conversions/UnknownStoredValue.cs:17, Throw<T> at :24-28), called on the right of a ??
because a converter body is an expression tree and cannot hold a throw (:10-16). Only a value
written outside EF can reach it, so the failure surfaces at the read rather than as a null member far
from it (EnumerationValueConverter.cs:27-35, :47); empty text in a name column still materializes
null (:70-73, :86-87).
Discovery runs through ModelBuilderExtensions.ApplyAllConfigurations
(.../DbContexts/ModelBuilderExtensions.cs:10, an extension(ModelBuilder) block at :12), which the
base calls with an entity filter so each database's model receives only its own entities
(ApplicationDbContext.cs:1073-1107, filter application at ModelBuilderExtensions.cs:57-60), over the
assemblies supplied by IEntityConfigurationAssemblyProvider and
its DefaultEntityConfigurationAssemblyProvider
implementation (.../Persistence/DefaultEntityConfigurationAssemblyProvider.cs:12), which scans loaded
*.Infrastructure assemblies, excludes Common.Infrastructure itself, and appends whatever a host
registered through EntityConfigurationOptions
(DefaultEntityConfigurationAssemblyProvider.cs:16-21, options at
.../Persistence/EntityConfigurationOptions.cs:10). Two configurations ship inside the framework itself,
PushNotificationConfiguration and
UserNotificationConfiguration
(.../Configuration/EntityTypeConfiguration/Notifications/PushNotificationConfiguration.cs:16,
.../UserNotificationConfiguration.cs:15), both tagged [UseDatabase("Notification")] and re-declaring
the Notification schema because namespace derivation would otherwise resolve them to Common
(PushNotificationConfiguration.cs:8-15, :25). This engine-portability design is
ADR-018 (polyglot persistence); note
the current-reality caveat: the SQLite and Cosmos plumbing is shipped and tested, but every concrete
subclass of the SQLite and Cosmos configuration bases lives in Common's own test projects, so SQL Server
is the only engine backing production entities today.
Identity tables one database owns
Most of the framework's own tables are infrastructure every relational source needs. Five are not: refresh sessions, permission grants, view-as grants, passkey credentials and machine clients are all Identity-module data that exactly one database owns, so each is mapped on request rather than everywhere.
The three newer tables share one shape.
ViewAsGrantModelBuilderExtensions
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/ViewAsGrantModelBuilderExtensions.cs:17,
ADR-137) maps ViewAsGrants with the primary key as the per-request lookup (the token's vag claim),
plus a (TargetUserId, GrantedAt) history index and a GrantedAt retention index (:15-21, :36-53);
PasskeyCredentialModelBuilderExtensions
(.../Auth/PasskeyCredentialModelBuilderExtensions.cs:12, ADR-139) maps PasskeyCredentials with a
unique index on the WebAuthn credential id, because the assertion names the credential and never the
account, plus a per-user index for the list (:15-21, :37-51); and
MachineClientModelBuilderExtensions
(.../MachineClients/MachineClientModelBuilderExtensions.cs:12, ADR-140) maps MachineClients with a
unique index on the service account, one client per account because the account's role is the client's
whole authority (:15-24, :53). Each defaults to the dbo schema, and each file also declares the
model contributor that applies the mapping (ViewAsGrantModelContributor
at ViewAsGrantModelBuilderExtensions.cs:73,
PasskeyCredentialModelContributor at
PasskeyCredentialModelBuilderExtensions.cs:72,
MachineClientModelContributor at
MachineClientModelBuilderExtensions.cs:71), whose gates and phases are tabled in the base-context
section above; the machine-client one runs in BeforeEntityPasses (:74) so the client is treated like
any other auditable entity, and a host that never opts in keeps a byte-identical model.
Their stores resolve the holding database the way the refresh-session store does, the registry first and
then the feature's own DataSourceName. EFViewAsGrantStore
(.../Auth/EFViewAsGrantStore.cs:32), behind IViewAsGrantStore,
answers every read as if no grant existed while ViewAs:Enabled or ViewAs:HostsGrantStore is false
instead of querying a table that is not there, which is what lets the sign-in history read through it and
the controller actions bind the view-as service on every host (:14-27, :38-39);
EFPasskeyCredentialStore (.../Auth/EFPasskeyCredentialStore.cs:28),
behind IPasskeyCredentialStore, is registered on every host
by AddInfrastructure and inert there, since only AddPasskeys registers the ceremony service that reads
it and every caller sits behind Passkeys:Enabled (:12-23); and
EFMachineClientStore (.../MachineClients/EFMachineClientStore.cs:28), behind
IMachineClientStore, is registered only by AddMachineClients
and writes through the unit of work, so the audit interceptor stamps who created, rotated or revoked a
client (:12-23). The refresh-session store also carries one internal projection of its own,
SignInChainRow (.../Auth/EFRefreshSessionStore.cs:360): a sign-in id with the issue
instants of that sign-in's earliest retained and newest sessions, one row of its sign-in chain query
(:359-370).
Of the two older tables, the stored permission grants are the smaller half.
PermissionGrantModelBuilderExtensions
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PermissionGrantModelBuilderExtensions.cs:23,
table name at :18) maps the PermissionGrants table into one model, and its doc comment gives the
same reason the refresh-session mapper gives: mapping them everywhere would leave an empty
PermissionGrants table in every other module's migrations (:6-14). The opt-in is the
AddStoredPermissionGrants DI call registering
PermissionGrantModelContributor (:84), whose AppliesTo checks
only the source name rather than a second configuration flag (:75-81, gate at :90-91).
EFPermissionGrantStore (.../Auth/EFPermissionGrantStore.cs:35) reads and
writes that table, resolving which database holds it exactly as
EFRefreshSessionStore does (the registry first, then the source
Authentication:PermissionGrants:DataSourceName names, :15-22), and reads untracked, the mirror
image of the refresh-session store's choice: a grant is inserted or deleted, never edited, so tracking
would only cost the change detector work on every snapshot load (:23-27). That snapshot is
PermissionGrantCache (.../Auth/PermissionGrantCache.cs:35), a singleton
that rebuilds the whole set in one query rather than lazy-loading per role, because the authorization
read is synchronous and a miss cannot go and fetch; a role whose last grant was deleted is evicted
in the same pass rather than left to expire, since a revoke that keeps granting until a TTL runs out
is the one staleness direction that is not safe (:14-31).
PermissionGrantRefreshService
(.../Auth/PermissionGrantRefreshService.cs:31) primes that snapshot at startup and rebuilds it on the
configured interval, so a grant added by another replica takes effect here without a restart, and a
failed load is logged and retried rather than fatal: authorization keeps working off the compiled
registry while the table is unreachable, so a database blip degrades the feature to "no stored grants",
a denied request an operator can see rather than a granted one nobody notices (:8-23).
Multi-device refresh sessions (ADR-097)
are the other half.
RefreshSessionModelBuilderExtensions
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:23)
maps the RefreshSession table on request rather than everywhere,
and the doc comment gives the reason: the outbox is infrastructure every relational source needs, while
refresh sessions are Identity-module data that exactly one database owns, so mapping them everywhere
would leave an empty RefreshSessions table in every other module's migrations (:6-14). It maps the
token hash as a fixed-width non-Unicode column, uniquely indexed because that is the lookup a refresh
answers and because a collision across users would let one account's token validate against another's
session (:44-49, :60-66), plus a (UserId, RevokedAt) index for the per-user family questions the
session cap, reuse detection and sign-out-everywhere all ask (:68-71). It reaches the model through
RefreshSessionModelContributor (:121), gated on
RefreshSessions:Enabled AND the source that setting names (:127-129), because a downstream app runs on
the sealed engine contexts and has no OnModelCreating of its own to override.
EFRefreshSessionStore (.../Auth/EFRefreshSessionStore.cs:31) is the
IRefreshSessionStore implementation over that table; it
resolves which database holds it the same way the rest of the framework routes an entity (the registry
first, then RefreshSessions:DataSourceName, :15-23) and reads tracked on purpose, because the
caller revokes by mutating the instances it hands back, with one read-only exception,
FindByIdUntrackedAsync, the re-read for the rotation loser (:25-29).
RefreshSessionCleanupService (.../Auth/RefreshSessionCleanupService.cs:48)
hard-deletes spent rows past RetentionDays: the row is bookkeeping, not an aggregate, and its content
is a credential digest plus the IP and user agent of a device, so keeping it past its usefulness is both
a growing table and a growing set of records describing a data subject
(ADR-005, :14-23). Its own doc
comment names the trade the retention window makes: a rotation chain older than the window is gone, so a
replay of a token that old reads as an unknown token instead of signalling reuse (:25-30). That is
[Rubric §11, Security] meeting [Rubric §30, Compliance and Data Governance] again, in a table rather
than in an interceptor.
Encryption, seeding, design time, and the shared helpers
A handful of supporting pieces round out the EF side. EncryptedStringConverter
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Encryption/EncryptedStringConverter.cs:76)
is a value converter that transparently encrypts a string column with authenticated AES-256-GCM. The stored
value is a versioned Base64 envelope, a one-byte key version, a random 12-byte nonce, the ciphertext, then a
16-byte tag, with the version byte passed to AES-GCM as associated data so it is covered by the
authentication tag and a rewritten version byte fails decryption instead of silently selecting a different
key (:38-44, envelope assembled at :204-210). A converter is built over either a single key, registered
as version 1 (:94-97), or a whole key ring plus a current version so reads resolve their key from the
version byte stored with each value and rotation needs no downtime (:109-112), and it rejects any key that
is not exactly 32 bytes on both paths (:127-141, :146-181). Its own doc comment states the constraint
that governs where it may be used: the ciphertext is non-deterministic, so the column cannot back equality
predicates, unique indexes, or server-side sorting (:19-32). It is the [Rubric §11, Security] control that
IAnonymizable points at for fields that must remain
retrievable after erasure. Its current reality matches
ADR-037: it is shipped and
unit-tested but unadopted, no entity configuration wires it (the only non-test references are its own
file and the IAnonymizable doc comment). On the read side, IQueryableExecutor
and its implementation EFQueryableExecutor (.../Persistence/EFQueryableExecutor.cs:11)
abstract async query materialization so higher layers can execute an IQueryable without referencing EF,
detecting a real EF query by its IAsyncEnumerable<T> implementation and degrading to LINQ-to-Objects
otherwise (EFQueryableExecutor.cs:43). That is what makes the specification evaluation in
Group 03 unit-testable without a database, a small but real
[Rubric §14, Testability] win. Two more helpers sit at this level:
SqlServerUniqueConstraintViolationDetector
(.../Persistence/SqlServerUniqueConstraintViolationDetector.cs:31) is the
IUniqueConstraintViolationDetector implementation that classifies
a duplicate-key failure by SQL Server error number 2601 or 2627, walking the whole inner-exception chain
and falling back to the message text so a wrapped or non-SQL-Server provider failure still classifies
(:34-40, :47-73); and ProfilingHelper (.../Persistence/ProfilingHelper.cs:9)
is the MiniProfiler step wrapper the repository decorators share (:11-31).
The framework's shared base for fixed-interval sweeps,
PeriodicBackgroundService, is a
scheduling type documented in Group 14, and
ADR-052 covers in-process
background work generally.
Seeding and design time close the loop. The abstract DbSeeder base
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Seeding/DbSeeder.cs:11)
declares the module seeder's SeedAsync (:18) and gives it a GetId<TIdentifier> helper that maps
integer seed ids to either int or a deterministic Guid so seed data reproduces across key
strategies (:20-47), plus SaveToleratingConcurrentSeedAsync (:76), which treats a unique or
primary-key violation as a lost race against a replica seeding the same rows: it detaches the pending
entries of the failed save and returns false instead of failing startup, classifying the violation
through the unit of work's IUniqueConstraintViolationDetector
when one is exposed, else through
SqlServerUniqueConstraintViolationDetector
(:49-75), and
IdentityModuleDbSeederBase<TUser>
(.../Seeding/IdentityModuleDbSeederBase.cs:57) hoists the repeated account-seeding idiom out of the two
app identity modules, leaving only app-specific hooks (Accounts at :83, EmailExistsAsync at :114,
CreateUser at :123) and a ShouldSeed opt-in gate that defaults to true (:90) and is checked first
in SeedAsync (:93-104), each account described by a SeedAccount record
(.../Seeding/SeedAccount.cs:17) whose own remarks warn that seed credentials are plaintext by
construction and therefore development-only data (:6-11). For migrations,
DesignTimeDbContextHelper
(.../DbContexts/Design/DesignTimeDbContextHelper.cs:41) builds a
SQLServerDbContext for dotnet ef without the app's DI container: a downstream
migrations project writes a few-line IDesignTimeDbContextFactory (:18-32, entry points at :50 and
the SQLite twin at :71), and dotnet ef migrations add X -- --datasource Conference selects which
physical source to build against (:165-181), so each database gets its own migrations project. It
composes minimal stand-ins (ExplicitAssemblyProvider at :185,
NullDomainEventDispatcher at :190) and a
DesignTimeDbContextOptions
(.../Design/DesignTimeDbContextOptions.cs:11) carrying the connection settings, then wires the same
DataSourceResolver and
EntityDataSourceRegistry the runtime uses so the design-time model matches
the runtime one (BuildDesignTimeServices, :134-232). It registers the tenant interceptor and the
audit-trail interceptor unconditionally so the design-time save pipeline matches the runtime one
(:168-180), and it adds each optional table as the same model contributor the feature's runtime
AddX call registers, one per Enable* flag on the options, over settings that say "on, here"
(:182-209, helper at :237-242); a flag left off adds nothing, which is exactly a host that never
opted in. The source name those settings carry is the physical one this context resolved to, never
the logical one asked for, because a logical source sharing the default connection collapses onto
Default and a contributor gated on the logical name would decline, leaving the scaffold without a
table the runtime model has (:154-158, :191). A host's own contributors follow, added through
DesignTimeDbContextOptions.AddModelContributor
(DesignTimeDbContextOptions.cs:264-278), because a contributor registered at runtime but omitted here
makes the scaffolded migrations and the running model disagree (:258-262, applied at
DesignTimeDbContextHelper.cs:212-215).
The storage, image, and push contracts
The group also carries the Application-layer contracts for the storage-adjacent services that are not EF at
all. Each has a null default in the container so a host that has not configured the backend still starts and
degrades cleanly, and the cloud-adapter (Azure Blob, Amazon S3, Google Cloud Storage) and null
implementations behind them are composition-side types documented in
Group 14.
IFileStorageService
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/IFileStorageService.cs:15)
stores and deletes blobs behind a Result-returning API and
exposes an IsConfigured flag handlers can gate features on (:18), false until a host registers one
of those adapters (:8-13). The dependency-free
ImageContentSniffer
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/ImageContentSniffer.cs:9)
is the upload-side guard, deciding the accepted formats (JPEG, PNG, WebP) from magic bytes rather than
the client-declared content type or file extension, before the content is stored or handed to the
caller's own image normalizer (:4-7, :14-35). It is
ADR-045, and squarely
[Rubric §11, Security]: the bytes, not the label, decide what a payload is. Three more dependency-free
helpers sit beside it, all ADR-045.
DocumentContentSniffer
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/DocumentContentSniffer.cs:49)
is the document sibling of the image sniffer: a payload is accepted only when the actual bytes and
the file-name extension agree on one of the formats the caller allowed, so a .pdf name over zip bytes
or an executable renamed .docx is rejected, and the client-declared content type is never consulted
(:42-48). What a caller may allow is the [Flags] DocumentFormats enum in the
same file (:9-39, All at :39); an Office Open XML package is told from an ordinary renamed zip by
the [Content_Types].xml entry every package carries at its root (:51-55), and an archive declaring
more entries than the cap is rejected without inspecting them, because a genuine Office document holds
tens of parts and never thousands (:57-61). BlobNames
(.../Storage/BlobNames.cs:10) reduces a user-supplied file name to a blob-safe segment, since a blob
name is part of a URL and of a storage path: anything outside A-Z a-z 0-9 . _ - collapses to a single
-, consecutive dots collapse so no .. can appear, and nothing surviving means the file fallback
(:5-9, :12, :21-25). FileUploadOptions
(.../Storage/FileUploadOptions.cs:13) carries the response headers stored with the blob, because
how a browser treats the bytes on the way back out is a header decision: an RFC 6266
Content-Disposition for a document download (:28), a long Cache-Control for a content-addressed
asset (:34), and None (:21) to leave the store's own defaults in place. On the push side,
INativePushSender
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/INativePushSender.cs:12)
and IPushDeviceRegistrar
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/IPushDeviceRegistrar.cs:12)
describe OS-level delivery and the device-installation registry that backs it
(ADR-044). A send does not throw:
SendToUsersAsync returns a NativePushOutcome
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/NativePushOutcome.cs:9)
carrying Android and Apple NativePushPlatformCounts (Sent, Failed and
the derived Attempted, .../Notifications/NativePushPlatformCounts.cs:9-13), each null when nothing was
attempted on that platform, plus the first failure met and a HasFailures roll-up, so a failing platform
is visible to the caller without stopping the other platform or the other legs (NativePushOutcome.cs:3-31,
the empty None at :12). The counts are in the provider's own unit, named by
NativePushDeliveryUnit (.../Notifications/NativePushDeliveryUnit.cs:4):
Batch for an Azure Notification Hubs tag-expression chunk, Endpoint for an SNS mobile-push endpoint
and Message for a Firebase Cloud Messaging registration token (:6-16). This channel sits beside the
persisted notification record and the SignalR path in Group 10.
One more Application interface sits in this group's persistence namespace without being repository-shaped
at all. IOutboxAdministration
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IOutboxAdministration.cs:16)
is the operator surface that gives an undelivered event a way back into delivery, projecting each abandoned
row into an OutboxDeadLetter record (:80) that deliberately omits the payload,
because it can carry personal data and no replay decision depends on reading it (:69-79). It is
[Rubric §13, Observability and Operability] material; the rows it administers are written by this group's
domain-event interceptor and delivered by the processor and consumers in
Group 04.
Where this group sits
Persistence is the concrete floor the abstract domain stands on. The entity bases and audit contracts from
Group 02 are what the interceptors stamp and the query filters hide;
the domain events aggregates raise are what
DomainEventSaveChangesInterceptor drains into the outbox that
Group 04 delivers; the transactional decorator in
Group 05 is what opens the transaction whose commit releases the deferred
dispatch; the specifications and query service in Group 03 are
evaluated by this group's SpecificationEvaluator against its repositories and
IQueryable surfaces; the refresh-session table this group maps is read and written by the auth stack in
Group 08; the navigation populators in Group 11
fill the cross-source gaps the degrade convention opens; the scheduler this group's gated tables answer to
lives in Group 14, which also composes the storage, push, and
event-consumer implementations behind the contracts this group declares; and the entity-source registry
answers the .Include() questions the populators ask. The design axes here are three orthogonal
ones collapsed behind a single DataSourceKey plus a scoped tenant:
ADR-006's Name axis (which database),
ADR-018's Engine axis (which storage
technology), and ADR-073's tenant axis
(whose rows, and optionally whose database), so application code never has to know which it is running on.
Read this group as the answer to one question the rest of the guide keeps asking: how does a framework that
describes persistence in pure domain terms actually put a row in a database, and do it in a way that
survives a module being pulled out into its own service.
IChannelJoinAuthorizer
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/IChannelJoinAuthorizer.cs:15· Level 0 · interface
- What it is: an optional entitlement check consulted before a SignalR connection is allowed to join a live channel, so channel membership is not decided by the channel-key shape pattern alone.
- Depends on:
ClaimsPrincipal(BCL) for the caller's identity; otherwise no first-party types. - Concept introduced, closing the gap between a shape-valid channel key and an authorized one.
[Rubric §11, Security]assesses whether an authorization decision that a hub cannot make structurally (any well-formed key likeevent:42passes the configured pattern) is pushed out to a pluggable check rather than left implicit. The doc comment (IChannelJoinAuthorizer.cs:17-24) frames the contract as a single yes/no gate: given the connection's principal and the requestedchannelKey, decide whether the connection may join. Because the parameter is optional and defaults tonullon the consuming hub, an existing host that never registers an implementation keeps working unchanged and every authenticated caller may join any well-formed channel key; a host that publishes anything not public to every signed-in user must register one deliberately. - Walkthrough: one method.
CanJoinAsync(ClaimsPrincipal? user, string channelKey, CancellationToken cancellationToken = default)(IChannelJoinAuthorizer.cs:25-28): returnstrueto admit the connection tochannelKey.useris the connection's principal (the hub requires authentication, so this is never null in practice);channelKeyis the caller-requested channel, already validated against the shape pattern before this check runs.
- Why it's built this way: keeping the check as a single optional interface, rather than a required
constructor argument, lets
NotificationHubship with a permissive default (NotificationHub.cs:20-25) while still giving a host with tenant- or role-scoped channels a single extension point to close the gap; the doc comment is explicit that the shape pattern alone is not authorization. See ADR-039 for the live-channel-push design this sits inside. - Where it's used: injected as the optional
joinAuthorizerparameter ofNotificationHub(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/NotificationHub.cs:38), consulted before admitting a join (NotificationHub.cs:211-227); with none registered the join is refused (fail closed,NotificationHub.cs:213-217). MMCA.ADC is the first registered implementation:LiveChannelJoinAuthorizer(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Live/LiveChannelJoinAuthorizer.cs:50-53) is wired withAddScoped<IChannelJoinAuthorizer, LiveChannelJoinAuthorizer>()(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:132).
NativePushDeliveryUnit
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/NativePushDeliveryUnit.cs:4· Level 0 · enum
- What it is: the unit a
NativePushOutcomecounts in, which differs by provider (NativePushDeliveryUnit.cs:3). - Depends on: nothing first-party.
- Concept introduced: none of its own; it qualifies the per-platform counts taught under
NativePushOutcome. A count of 3 means three different things depending on the adapter, so the outcome carries the unit beside the numbers rather than pretending they are comparable. - Walkthrough: four members.
None = 0(NativePushDeliveryUnit.cs:7): nothing was attempted.Batch = 1(NativePushDeliveryUnit.cs:10): one send per batch of users, the Azure Notification Hubs shape (one tag-expression chunk per platform).Endpoint = 2(NativePushDeliveryUnit.cs:13): one send per device endpoint, SNS mobile push.Message = 3(NativePushDeliveryUnit.cs:16): one send per registration token, Firebase Cloud Messaging.
- Why it's built this way: the three adapters behind
INativePushSenderfan out differently, and naming the unit keeps a stored outcome honest about what was counted (ADR-044). - Where it's used:
AzureNotificationHubNativePushSenderreportsBatch(MMCA.Common/Source/Hosting/MMCA.Common.Azure/Notifications/AzureNotificationHubNativePushSender.cs:69),SnsNativePushSenderreportsEndpoint(MMCA.Common/Source/Hosting/MMCA.Common.Aws/Notifications/SnsNativePushSender.cs:193) andFcmNativePushSenderreportsMessage(MMCA.Common/Source/Hosting/MMCA.Common.Gcp/Notifications/FcmNativePushSender.cs:88).DeliverPushNotificationPageInternalCommandHandlerstores the unit's name on the notification row only when it is notNone(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:202).
NativePushPlatformCounts
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/NativePushPlatformCounts.cs:9· Level 0 · record struct
- What it is: one platform's sent and failed counts inside a
NativePushOutcome(NativePushPlatformCounts.cs:5). - Depends on: BCL only (
System.Runtime.InteropServicesfor[StructLayout(LayoutKind.Auto)],NativePushPlatformCounts.cs:1,8). - Concept introduced: none; see
NativePushOutcomefor the per-platform outcome. - Walkthrough: a positional
readonly record structwith two members and one derived property.Sent(NativePushPlatformCounts.cs:9): sends the provider accepted (NativePushPlatformCounts.cs:6).Failed(NativePushPlatformCounts.cs:9): sends the provider refused or that never reached it (NativePushPlatformCounts.cs:7).Attempted(NativePushPlatformCounts.cs:12):Sent + Failed.
- Why it's built this way: a small value type with value equality, so tests can compare an expected count pair directly and an outcome stays allocation-light.
- Where it's used: the nullable
AndroidandAppleproperties ofNativePushOutcome(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/NativePushOutcome.cs:15,18), built byNativePushOutcome.From(NativePushOutcome.cs:53-54).
NativePushOutcome
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/NativePushOutcome.cs:9· Level 1 · record
- What it is: what one
INativePushSenderSendToUsersAsynccall achieved: per platform, how many sends succeeded and failed, in the provider's unit, plus the first failure (NativePushOutcome.cs:3-8). - Depends on:
NativePushPlatformCounts,NativePushDeliveryUnit, andSystem.Exception. - Concept introduced, a delivery outcome returned instead of thrown.
[Rubric §29, Resilience & Business Continuity]assesses whether a partial failure in a fan-out is contained and made visible rather than aborting the whole operation. A sender returns this record instead of throwing, so a failing platform is visible to the caller without stopping the other platform or the other delivery legs (NativePushOutcome.cs:6-7). The failure is still carried, as data: the first exception the sender met. - Walkthrough:
None(NativePushOutcome.cs:12): a shared instance for a call that attempted nothing (no adapter, or no installations).Android,Apple(NativePushOutcome.cs:15,18): nullable counts; null means nothing was attempted on that platform.Unit(NativePushOutcome.cs:21): theNativePushDeliveryUnitthe counts are expressed in.FirstFailure(NativePushOutcome.cs:28): the first failure, set whenever a send failed, including one the sender could not attribute to a platform (a failed installation lookup, say;NativePushOutcome.cs:23-27).HasFailures(NativePushOutcome.cs:31): true whenFirstFailureis set or either platform has a nonzeroFailed.From(unit, androidSent, androidFailed, appleSent, appleFailed, firstFailure)(NativePushOutcome.cs:43-56): the factory adapters use; a platform whose sent plus failed is zero is left null (NativePushOutcome.cs:53-54).
- Why it's built this way: native delivery is best-effort beside the persisted inbox and SignalR legs (ADR-044); returning counts lets the caller record what happened on the notification row instead of only logging an exception.
- Where it's used: returned by every sender:
Task.FromResult(NativePushOutcome.None)inNullNativePushSender(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/NullNativePushSender.cs:16),Fromin the Azure and SNS adapters (AzureNotificationHubNativePushSender.cs:69,SnsNativePushSender.cs:193), and an object initializer in the FCM adapter (FcmNativePushSender.cs:88).DeliverPushNotificationPageInternalCommandHandlerreads it once per delivery page and, when it carries counts or a failure, callsPushNotification.AddNativePushOutcome(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:189-207), then logsFirstFailureas a Warning (DeliverPushNotificationPageInternalCommandHandler.cs:209-212,251).
INativePushSender
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/INativePushSender.cs:12· Level 2 · interface
- What it is: the contract for sending OS-level push notifications to registered device installations, the delivery channel that reaches a phone when the app is backgrounded or killed.
- Depends on:
NativePushOutcome(its return type) and theUserIdentifierTypeglobal alias (INativePushSender.cs:26, see primer §2); BCL otherwise. Its registry counterpart isIPushDeviceRegistrar. - Concept introduced, native push as the third delivery channel.
[Rubric §6, CQRS & Event-Driven Design]assesses whether a delivery mechanism is a swappable abstraction declared in Application and implemented at the edge rather than a hardcoded SDK call inside a handler. The doc comment (INativePushSender.cs:3-11) places this beside the two other channels under ADR-044: the persisted inbox record and the SignalR real-time push handled byIPushNotificationSender. Where SignalR reaches a connected browser, native push reaches a device that is not running the app. Adapter packages supply the implementation: MMCA.Common.Azure targets Azure Notification Hubs and MMCA.Common.Aws targets SNS mobile push (both FCM v1 plus APNs), and MMCA.Common.Gcp targets Firebase Cloud Messaging with FCM registration tokens on both platforms (INativePushSender.cs:7-10). The default registration is a no-op until an adapter is configured. - Walkthrough: one method, returning a
NativePushOutcomerather than aResult.Task<NativePushOutcome> SendToUsersAsync(IEnumerable<UserIdentifierType> userIds, string title, string body, Dictionary<string, string>? metadata = null, CancellationToken cancellationToken = default)(INativePushSender.cs:26): targets specific users, resolved to installations via user tags (INativePushSender.cs:20);metadatacarries optional key-value data such as a deep-link route in the platform payload (INativePushSender.cs:23). The contract (INativePushSender.cs:14-19): a failing send is counted and the rest still go out, the failure comes back inNativePushOutcome.FirstFailureinstead of being thrown, and only the caller's own cancellation propagates.NativePushOutcome.Noneis the answer when nothing was attempted (INativePushSender.cs:25).
- Why it's built this way: targeting users rather than raw device tokens keeps the caller out of the tag
and token bookkeeping, which
IPushDeviceRegistrarowns; returning an outcome instead of throwing keeps one bad platform or token from hiding the sends that worked; the no-op default makes native push an opt-in capability rather than a hard dependency of every host (ADR-134 keeps the vendor SDKs out of the core). - Where it's used: injected into
DeliverPushNotificationPageInternalCommandHandler(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/DeliverPushNotificationPageInternalCommandHandler.cs:51) alongside the SignalR sender and called once per delivery page atDeliverPushNotificationPageInternalCommandHandler.cs:189; the handler still wraps the call in a best-effort catch (DeliverPushNotificationPageInternalCommandHandler.cs:214-219).SendPushNotificationHandlerno longer takes the sender: it persists the audit row and schedules the first page (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/UseCases/Send/SendPushNotificationHandler.cs:47-52,110-111).NullNativePushSenderis registered by default withTryAddTransient(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:425) and an adapter call replaces it:AzureNotificationHubNativePushSender(MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:135),SnsNativePushSender(MMCA.Common/Source/Hosting/MMCA.Common.Aws/AwsServiceCollectionExtensions.cs:194) orFcmNativePushSender(MMCA.Common/Source/Hosting/MMCA.Common.Gcp/GcpServiceCollectionExtensions.cs:166).CloudAdapterTripwirefails startup whenNativePush:Enabledis true but the resolved sender is still the no-op (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/CloudAdapterTripwire.cs:77-82).
IPushDeviceRegistrar
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Notifications·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Notifications/IPushDeviceRegistrar.cs:12· Level 3 · interface
- What it is: maintains the device-installation registry behind
INativePushSender, tagging each installation with its owning user so sends can target users rather than raw device tokens. - Depends on:
Result(viaMMCA.Common.Shared.Abstractions,IPushDeviceRegistrar.cs:1),DeviceInstallationRequest(fromMMCA.Common.Shared.Notifications.PushNotifications,IPushDeviceRegistrar.cs:2), and theUserIdentifierTypealias (IPushDeviceRegistrar.cs:30). - Concept introduced, ownership scoping on a client-supplied identifier, and the existence-oracle problem.
[Rubric §11, Security]assesses whether a resource identifier supplied by a caller is authorized against that caller before it is acted on, and whether error responses leak the existence of other users' resources. Installation ids are client-generated, so nothing stops a caller from sending someone else's; the delete verifies theuser:{id}tag stamped byUpsertAsyncbefore deleting, and reports a mismatch as success rather than not-found, because answering differently for "no such installation" and "not yours" would turn the endpoint into an existence oracle for other users' installation ids, and the caller has nothing to do with either answer (IPushDeviceRegistrar.cs:40-48). The stronger property is structural: every delete is scoped to an owner, there is no unscoped form, so an implementation cannot skip the check by accident (IPushDeviceRegistrar.cs:43-44).[Rubric §6, CQRS & Event-Driven Design]also applies: the type doc (IPushDeviceRegistrar.cs:6-11, ADR-044) explains the split, where this type owns the installation registry, tagged by user, soINativePushSendercan send to users, and the default implementation is a no-op until a native push adapter is configured (MMCA.Common.Azure, MMCA.Common.Aws or MMCA.Common.Gcp). - Walkthrough: three methods, all returning
Result.UpsertAsync(UserIdentifierType userId, DeviceInstallationRequest request, CancellationToken cancellationToken = default)(IPushDeviceRegistrar.cs:30): creates or refreshes an installation, tagging it with the authenticated owner (IPushDeviceRegistrar.cs:14-17). The installation id is per device: an id already owned by another user is handed over to the caller when the request presents the installation's current push channel (the same device changing hands). Without the channel the upsert does not overwrite and returns anErrorType.Conflicterror, and the client mints a new installation id and retries (IPushDeviceRegistrar.cs:18-29). Unlike the delete, a conflict is not an existence oracle worth hiding, because ids are random client-generated GUIDs, not enumerable values (IPushDeviceRegistrar.cs:27-28).DeleteAsync(UserIdentifierType userId, string installationId, CancellationToken cancellationToken = default)(IPushDeviceRegistrar.cs:49): the ownership-scoped single delete. Unknown installation ids and installations owned by another user both succeed without deleting anything (IPushDeviceRegistrar.cs:32-35).DeleteAllForUserAsync(UserIdentifierType userId, CancellationToken cancellationToken = default)(IPushDeviceRegistrar.cs:66): the account-erasure counterpart, deleting every installation the user owns so a device still signed in elsewhere stops receiving pushes addressed to the erased account (IPushDeviceRegistrar.cs:51-55). It is owner-scoped too: an installation is found through the owner'suser:{id}stamp and deleted only while it still carries it, so one handed over to another user in the meantime survives. It is idempotent (already-deleted installations are simply no longer found), and a user with no installations is a success (IPushDeviceRegistrar.cs:58-64).
- Why it's built this way: separating the registry (this type) from the send
(
INativePushSender) means the send API can target users while token bookkeeping stays in one place. Making the owner a required parameter of every delete member is what removes the class of bug where a caller passes a raw client-supplied id straight through: there is no unscoped overload to pass it to. Idempotency on the bulk delete is what lets erasure retry it through a durable internal command. - Where it's used:
DevicesControllerinjects it (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/DevicesController.cs:27) and passes the authenticated user id on both calls,UpsertAsyncatDevicesController.cs:49andDeleteAsyncatDevicesController.cs:73.DeleteUserPushInstallationsInternalCommandHandlercallsDeleteAllForUserAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserPushInstallationsInternalCommandHandler.cs:31) and returns a failure unchanged so the internal-command processor retries it; theDeleteUserPushInstallationsInternalCommandis scheduled by account erasure (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:192).NullPushDeviceRegistraris the default registration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:426); an adapter call replaces it:AzureNotificationHubDeviceRegistrar(MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:136),SnsPushDeviceRegistrar(MMCA.Common/Source/Hosting/MMCA.Common.Aws/AwsServiceCollectionExtensions.cs:195) orFcmPushDeviceRegistrar(MMCA.Common/Source/Hosting/MMCA.Common.Gcp/GcpServiceCollectionExtensions.cs:167). On a host with no push adapter the erasure command completes having deleted nothing, so it must run on the host that registers the adapter (DeleteUserPushInstallationsInternalCommandHandler.cs:16-17).
DataSource
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IDataSourceService.cs:6· Level 0 · enum
- What it is: a four-value enum (
CosmosDB,Sqlite,SQLServer,PostgreSQL) naming which database engine persists a given entity type. It shares a file withIDataSourceService: the enum atIDataSourceService.cs:6, the interface atIDataSourceService.cs:31. - Depends on: nothing first-party. The file has no
usingdirectives at all (IDataSourceService.cs:1is the namespace declaration), which is the point: this is the Application layer's vocabulary for a persistence decision, with no persistence library behind it. - Concept introduced, database-per-service routing at the entity level.
[Rubric §8, Data Architecture]assesses whether storage is deliberately partitioned, whether the routing strategy is explicit, and whether cross-database JOINs happen by accident; this enum is where that decision becomes a first-class value the query pipeline can branch on.[Rubric §7, Microservices Readiness]assesses whether a module could be lifted out without a rewrite; because each module owns its own store (ADR-006), the engine is a per-entity fact rather than a global one. The values encode a capability, not just a name: theCosmosDBdoc comment says "document store, no cross-container JOINs" (IDataSourceService.cs:8), whileSqlitesupports "JOINs within a single database file" (IDataSourceService.cs:11),SQLServerhas "full relational JOIN support" (IDataSourceService.cs:14), andPostgreSQLhas the same full relational JOIN support (IDataSourceService.cs:18). That distinction is what lets the framework decide whether a navigation can be an EF.Include()or must become a manual batch load. ADR-113 records PostgreSQL's addition as a first-class engine alongside the original three. - Walkthrough: four members, each documented with its JOIN capability.
CosmosDB(IDataSourceService.cs:9),Sqlite(IDataSourceService.cs:12),SQLServer(IDataSourceService.cs:15), andPostgreSQL(IDataSourceService.cs:22).PostgreSQLis appended afterSQLServerrather than inserted alphabetically: the doc comment on the member says why (IDataSourceService.cs:17-21), the three original members are shipped public API with fixed ordinal values, and renumbering them would break every consumer that persisted or serialized one. There is noNone/Unknownmember and no explicit numeric assignment, soCosmosDBis the default0value. - Why it's built this way: encoding the JOIN-capability difference in the enum lets
IDataSourceService.HaveIncludeSupport(IDataSourceService.cs:61) answer the include-versus-batch-load question from a value comparison rather than a scattered chain of provider checks, and it keeps that decision in the framework-pure Application layer with no EF Core reference. - Where it's used: paired with a database name in
DataSourceKey(DataSourceKey.cs:15); resolved and compared byIDataSourceService; mapped per entity byEntityDataSourceRegistry; consumed byNavigationMetadataProviderto classify each navigation as an EF include or a manual populate.
IConcurrencyConflictDetector
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IConcurrencyConflictDetector.cs:23· Level 0 · interface
- What it is: a one-method classifier that answers whether a failed save was rejected because of an optimistic-concurrency conflict, so a handler recovering from a lost race can recognise the collision without depending on the provider exception type that reported it.
- Depends on: nothing first-party. The single method takes a BCL
Exception(IConcurrencyConflictDetector.cs:23). - Concept introduced, classifying a concurrency failure without naming the provider.
[Rubric §3, Clean Architecture]assesses whether technology details stay outside the inner layers: EF Core'sDbUpdateConcurrencyExceptionis a provider type, and this interface lets Application recognise the failure by asking the question rather than catching the concrete type.[Rubric §29, Resilience & Business Continuity]applies to how a handler reacts to a lost race: the interface mirrorsIUniqueConstraintViolationDetectorin shape and intent, one boolean classifier over an exception chain, so the same recovery pattern serves two different failure modes. - Walkthrough: one method,
bool IsConcurrencyConflict(Exception exception)(IConcurrencyConflictDetector.cs:25). The doc comment states the contract on the parameter (IConcurrencyConflictDetector.cs:16-19): the answer coversexceptionor anything in its inner-exception chain, which is what makes it usable against a wrapped save failure. It is synchronous and takes no cancellation token, since it inspects an object already in hand. - Why it's built this way: declaring the question in Application and answering it in Infrastructure, where the provider exception type is already referenced, keeps the classification swappable per engine while every handler that recovers from a concurrency conflict keeps working unchanged (ADR-035).
- Where it's used: implemented by
EfCoreConcurrencyConflictDetector(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EfCoreConcurrencyConflictDetector.cs:2), registered inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs. Consumed by MMCA.ADC'sRefreshFromSessionizeHandlerto distinguish a concurrency conflict from other save failures during a Sessionize refresh (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/RefreshFromSessionize/RefreshFromSessionizeHandler.cs:1), registered byMMCA.ADC.Conference.Infrastructure'sDependencyInjection.
IEntityConfigurationAssemblyProvider
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IEntityConfigurationAssemblyProvider.cs:10· Level 0 · interface
- What it is: a single-method contract returning the assemblies that hold EF Core entity type configurations, so a DbContext can discover and apply them without hardcoding module assembly-name patterns.
- Depends on:
System.Reflection(BCL) only (IEntityConfigurationAssemblyProvider.cs:1). - Concept introduced, a module-agnostic model surface that keeps EF out of Application.
[Rubric §3, Clean Architecture]assesses whether the inner layers declare intent while the outer layers own the technology; here Application declares which assemblies carry configurations and Infrastructure performs the EF scan.[Rubric §7, Microservices Readiness]assesses extraction cost: each module ships its ownIEntityTypeConfiguration<T>classes in its own Infrastructure assembly, so removing a module from the returned list removes it from the model, no context rewrite required. The doc comment states exactly this framing (IEntityConfigurationAssemblyProvider.cs:5-9). - Walkthrough: one method,
IReadOnlyList<Assembly> GetConfigurationAssemblies()(IEntityConfigurationAssemblyProvider.cs:15). It takes no arguments and no cancellation token: the assembly set is a composition-time fact, resolved once, not a per-request query. - Why it's built this way: routing configuration discovery through an injected provider means the active module set determines the model without any context knowing a module by name, which is the extraction invariant behind ADR-006 and ADR-007.
- Where it's used: injected into
ApplicationDbContext(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:47) and each engine subclass (SQLServerDbContextatSQLServerDbContext.cs:18,CosmosDbContextatCosmosDbContext.cs:18,SqliteDbContextatSqliteDbContext.cs:15); consumed byEntityDataSourceRegistryto build the entity-to-source map (EntityDataSourceRegistry.cs:22) and byPhysicalDbContextFactory(PhysicalDbContextFactory.cs:22). The default implementationDefaultEntityConfigurationAssemblyProvideris registered withTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:61), andDesignTimeDbContextHelpersubstitutes its own nestedExplicitAssemblyProviderfordotnet efruns (DesignTimeDbContextHelper.cs:217and:185).
IQueryableExecutor
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IQueryableExecutor.cs:7· Level 0 · interface
- What it is: an abstraction over the EF Core
IQueryableoperations the Application layer needs (Include,AsSplitQuery,ToListAsync,CountAsync) that would otherwise require a directMicrosoft.EntityFrameworkCorereference there. - Depends on:
System.Linq(BCL) only; the file declares nousingdirectives. - Concept introduced, inverting EF's terminal operators out of Application.
[Rubric §3, Clean Architecture]assesses whether the inner layers stay free of framework dependencies; EF's async materializers (ToListAsync,CountAsync) andIncludeare extension methods living in the EF assembly, so calling them directly would drag EF into Application. This interface inverts that: Infrastructure implements each by calling EF, and Application receives the interface by DI. The doc comment (IQueryableExecutor.cs:3-6) states exactly that intent. - Walkthrough: four methods; the two queryable transforms are constrained
where T : class(IQueryableExecutor.cs:19and:31) because EF requires a reference type there, while the two materializers accept anyTso a projection to a scalar or DTO still works.Include<T>(IQueryable<T> query, string navigationPropertyPath)(IQueryableExecutor.cs:18): a string-based include path, for example"Category"or"Order.OrderLines"(IQueryableExecutor.cs:16), deliberately not a lambda, because the generic query pipeline builds include paths at runtime from navigation-property name strings. The doc comment (IQueryableExecutor.cs:9-13) adds that the EF implementation also switches the query to split-query mode when the path reaches a collection, using the same heuristic as specification includes:EFQueryableExecutor.Includeroutes the single path throughSpecificationEvaluator.ApplyIncludes, the one home of that heuristic, and leaves a non-EF queryable unchanged (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EFQueryableExecutor.cs:14-23).AsSplitQuery<T>(IQueryable<T> query)(IQueryableExecutor.cs:30): switches EF to split-query mode. The doc comment (IQueryableExecutor.cs:21-26) explains why it matters: paginating (Skip/Take) a query that has collection includes in single-query mode truncates or mis-correlates child rows, so list reads come back with empty collections. It is documented as a no-op for non-EF (in-memory) queryables.ToListAsync<T>(IQueryable<T> query, CancellationToken cancellationToken = default)(IQueryableExecutor.cs:38) andCountAsync<T>(IQueryable<T> query, CancellationToken cancellationToken = default)(IQueryableExecutor.cs:45): the async materializers.
- Why it's built this way: the string include path (rather than
Expression<Func<T, TProperty>>) is required because the query pipeline composes includes from runtime navigation metadata, not compile-time lambdas; and namingAsSplitQueryas an explicit operation keeps a well-known EF pagination defect from silently reaching list endpoints. - Where it's used: implemented by
EFQueryableExecutor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EFQueryableExecutor.cs:11), registered withTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:113). Injected intoEntityQueryPipeline(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:14) and into the framework's own notification handlers, for exampleGetMyNotificationsHandler(GetMyNotificationsHandler.cs:18).
IRawSqlQueryExecutor
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRawSqlQueryExecutor.cs:25· Level 0 · interface
- What it is: an escape hatch for interpolated raw SQL reads, materializing rows into a scalar or an
unmapped DTO, for the cases a
Queryable-based repository cannot express. - Depends on: nothing first-party; the interpolated statement type is the BCL
FormattableString. - Concept introduced, raw SQL as a declared, parameterized escape hatch.
[Rubric §11, Security]assesses whether raw SQL access is disciplined rather than ad hoc: both methods take aFormattableString, so every interpolation hole becomes a command parameter rather than a string-concatenated value, which is what keeps this interface off the path to SQL injection.[Rubric §3, Clean Architecture]assesses whether the inner layers stay technology-free; declaring the contract here and executing it in Infrastructure keepsMMCA.Common.Applicationfree of a direct ADO.NET or EF Core reference while still giving a handler a way to run a statement the query pipeline cannot translate. - Walkthrough: two methods, both generic in the row shape
T.QueryAsync<T>(FormattableString sql, CancellationToken cancellationToken = default)(IRawSqlQueryExecutor.cs:32): runs the statement and materializes every row intoT, empty when none match.QuerySingleOrDefaultAsync<T>(FormattableString sql, CancellationToken cancellationToken = default)(IRawSqlQueryExecutor.cs:40): runs a statement expected to select at most one row, throwingInvalidOperationExceptionwhen the statement selected more than one (IRawSqlQueryExecutor.cs:39).- Neither method documents a runtime "not relational" failure. The type-level remarks
(
IRawSqlQueryExecutor.cs:18-21) move that check to registration instead: the executor is registered only when the host's default physical data source is on a relational engine, so a Cosmos-default host (its own query language, no SQL command surface to parameterize) has no registration at all, and a service that injects this interface there fails when the container is validated. The gate isDataSourceEngines.For(defaultEngine).Capabilities.IsRelationalinMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:507.
- Why it's built this way: an interpolated
FormattableStringparameter, rather than a plainstringplus a parameter array, keeps the parameterization automatic at the call site: a developer writes ordinary string interpolation and the implementation is responsible for turning each hole into a command parameter before the statement reaches the database. - Where it's used: implemented by
EFRawSqlQueryExecutor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EFRawSqlQueryExecutor.cs:2), registered conditionally as scoped inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:509(covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/DependencyInjectionInfrastructureTests.cs). Exercised by the architecture fitness baseMMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Cqrs/RawSqlConventionTestsBase.csand its ADC concrete testMMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/RawSqlConventionTests.cs.
IUniqueConstraintViolationDetector
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IUniqueConstraintViolationDetector.cs:31· Level 0 · interface
- What it is: a one-method classifier that answers whether a failed save was rejected for violating a unique constraint, so a handler whose pre-check lost a race against a concurrent insert can recognise the collision and return the same conflict the pre-check would have produced.
- Depends on: nothing first-party. The file has no
usingdirectives at all, and the single method takes a BCLException(IUniqueConstraintViolationDetector.cs:42). - Concept introduced, classifying a provider error without naming the provider.
[Rubric §3, Clean Architecture]assesses whether technology details stay outside the inner layers, and the interface remarks make the constraint concrete (IUniqueConstraintViolationDetector.cs:10-20): the error identity lives in a provider type, SQL Server reports the collision asSqlException.Number2601 (unique index) or 2627 (primary key or unique constraint), and neither that type nor the EF CoreDbUpdateExceptionwrapping it is reachable fromMMCA.Common.Application, which referencesMMCA.Common.Domainand no data provider.[Rubric §15, Best Practices & Code Quality]assesses whether a behavior rests on something stable: reading the exception message from a handler is what the layering constraint used to force, and the remarks reject it twice over, because the wording is a provider and locale detail that can change under a working handler, and matching on it drags provider vocabulary into a persistence-neutral layer.[Rubric §29, Resilience & Business Continuity]applies to the failure mode chosen here: an unclassified exception simply propagates, so a miss is safe rather than silent and the caller sees exactly the failure it would have seen with no detection at all (IUniqueConstraintViolationDetector.cs:26-29). - Walkthrough: one method,
bool IsUniqueConstraintViolation(Exception exception)(IUniqueConstraintViolationDetector.cs:42). The contract is stated on the parameter rather than left to the implementation: the answer coversexceptionor anything in its inner-exception chain (IUniqueConstraintViolationDetector.cs:33-41), which is what makes it usable against EF's wrapping exception. It is synchronous and takes no cancellation token, because it inspects an object already in hand. - Why it's built this way: the question is declared in Application and answered in Infrastructure, where the
provider types are already referenced, so swapping engines swaps the implementation and every handler that
recovers from a lost insert race keeps working unchanged
(
IUniqueConstraintViolationDetector.cs:21-25). - Where it's used: implemented by
SqlServerUniqueConstraintViolationDetector(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SqlServerUniqueConstraintViolationDetector.cs:37), which walks the inner-exception chain (SqlServerUniqueConstraintViolationDetector.cs:63-83) matching the two error numbers (:34and:37) with a message fallback for engines that report the same rejection in words (:40,:43, matched at:63-64). It is registered withTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:123), deliberatelyTryAddso a host on another engine can register its own implementation first and keep it (DependencyInjection.cs:120-122). Consumers inject it into thewhenclause of a catch:GetOrCreateMyBadgeHandler(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/CheckIns/UseCases/GetOrCreateMyBadge/GetOrCreateMyBadgeHandler.cs:22and:53),CreateSessionHandler(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/Create/CreateSessionHandler.cs:30and:60, where the catch drives a bounded manual-id retry),CreateBookmarkHandler(CreateBookmarkHandler.cs:22),SetLeaderboardParticipationHandler(SetLeaderboardParticipationHandler.cs:36), andPointsAwarder(PointsAwarder.cs:39). The framework-level registration replaced per-module copies: the ADC Conference module records that it no longer carries its own pair (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Infrastructure/DependencyInjection.cs:28).
IUpdatePropertySetter<TEntity>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IUpdatePropertySetter.cs:13· Level 0 · interface
- What it is: a persistence-agnostic builder for the SET clause of a bulk update. A handler describes
which properties change and to what, and Infrastructure translates the description into the provider's
set-based
UPDATE. - Depends on:
System.Linq.Expressions(BCL,IUpdatePropertySetter.cs:1) only. It is the parameter type ofIWriteRepository.ExecuteUpdateAsync(IRepository.cs:491), which the doc comment cross-references (IUpdatePropertySetter.cs:7). - Concept introduced, describing a SET clause without leaking EF Core.
[Rubric §3, Clean Architecture]assesses whether the technology choice stays outside the inner layers;[Rubric §12, Performance & Scalability]assesses whether hot write paths avoid needless round trips, and a single set-based statement replaces the load, mutate, save cycle. The doc comment (IUpdatePropertySetter.cs:5-11) is explicit that the shape mirrors EF Core'sSetPropertyCallswithout referencing it, which is what keepsMMCA.Common.ApplicationEF-free while still offering EF's most useful bulk primitive. - Walkthrough: two
Setoverloads, both generic inTPropertyand both returningIUpdatePropertySetter<TEntity>so calls chain.Set<TProperty>(Expression<Func<TEntity, TProperty>> property, TProperty value)(IUpdatePropertySetter.cs:20-22): assigns a fixed value, for example a status or a timestamp.Set<TProperty>(Expression<Func<TEntity, TProperty>> property, Expression<Func<TEntity, TProperty>> valueFactory)(IUpdatePropertySetter.cs:33-35): assigns from an expression over the current database row. The doc comment (IUpdatePropertySetter.cs:24-28) gives the motivating case,quantity => quantity.Amount - 5, which becomes an atomic read-modify-write that the database itself arbitrates, so two racing callers cannot both win and no rowversion retry loop is needed.
- Why it's built this way: passing an
Action<IUpdatePropertySetter<TEntity>>(rather than a dictionary of property names or a prebuilt EF expression) keeps the call site strongly typed and refactor-safe while the concrete translation stays swappable per provider. - Where it's used: implemented by
UpdatePropertySetterBuilder<TEntity>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/UpdatePropertySetterBuilder.cs:14), which collects each assignment as a delegate (UpdatePropertySetterBuilder.cs:16) and replays them onto EF Core'sUpdateSettersBuilder<TSource>(UpdatePropertySetterBuilder.cs:52). It also records assigned property names (UpdatePropertySetterBuilder.cs:17and:64) and exposesSetsProperty(UpdatePropertySetterBuilder.cs:49) soEFRepository<TEntity, TIdentifierType>can stampLastModifiedOnandLastModifiedByonly when the caller did not (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:117-133), keeping audit fields correct on a path that bypasses the save pipeline (EFRepository.cs:22).
OutboxDeadLetter
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IOutboxAdministration.cs:122· Level 0 · record (sealed, positional)
- What it is: one dead-lettered outbox row flattened for an operator view: the handle to replay it, which source it came from, what it was, when it happened, how hard delivery was tried, and why the last attempt failed.
- Depends on: nothing first-party (BCL
GuidandDateTime). It is the element type returned byIOutboxAdministration.ListDeadLettersAsync(IOutboxAdministration.cs:33) and it shares that interface's file. - Concept introduced, projecting an operational row without projecting its payload.
[Rubric §30, Compliance, Privacy & Data Governance]assesses whether personal data is exposed only where it is needed; the type doc says outright that the event PAYLOAD is deliberately not projected, because it can carry personal data (ADR-005) and nothing an operator decides about a replay depends on reading it (IOutboxAdministration.cs:108-112).[Rubric §13, Observability & Operability]assesses whether an operator can see enough to act:RetryCountandLastErrorare what turn "this failed" into a decision,DeadLetterReasonsays which of the two abandonment paths fired, andOrderingKeysays whether the row belongs to an ordered stream. SeeOutboxMessagefor the persisted row this flattens. - Walkthrough: nine positional members, each documented on the record
(
IOutboxAdministration.cs:113-121):Id(:110), the outbox row id and the handleReplayDeadLettersAsynctakes;DataSource(:111), the source whose outbox table holds the row, and the same string thedataSourcefilters accept;EventType(:112), the stored event type name;OccurredOn(:113);RetryCount(:114), attempts made before the row was abandoned; the nullableLastError(:115) and nullableOrderingKey(:116);DeadLetteredOn(:117), the UTC instant the processor abandoned the row; and the nullableDeadLetterReason(:118), eitherretries_exhaustedortype_unresolvable(IOutboxAdministration.cs:120-121), the two reason constants the processor stamps (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:99,:105). - Why it's built this way: a positional record gives an immutable, structurally comparable read model for free, and keeping it in the Application layer beside its interface means an admin surface can render dead letters without referencing the EF entity or the Infrastructure assembly.
- Where it's used: built by the Infrastructure implementation's projection
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxAdministration.cs:127), from rows matching the dead-letter predicateProcessedOn == null && DeadLetteredOn != null(OutboxAdministration.cs:123), so a row is a dead letter because the processor stamped it, not because a retry count crossed a threshold at read time.DeadLetteredOnis read with!.Value(OutboxAdministration.cs:135), safe under that predicate. Rows are collected across sources and returned oldest first, ties broken by id (OutboxAdministration.cs:146).
DataSourceKey
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/DataSourceKey.cs:15· Level 1 · record struct (readonly)
- What it is: the identity of a physical data source, a (
DataSourceEngine,string Name) pair, whereNamedistinguishes multiple databases on the same engine ("database per microservice"). - Depends on:
DataSource(Level 0, same namespace). Nousingdirectives at all. - Concept, physical-key comparison as the include-support test.
[Rubric §8, Data Architecture]assesses explicit storage partitioning and routing. Areadonly record structgives correct structural equality with zero boilerplate, which is the whole point: Application code that needs to know whether two entities can be joined compares theirDataSourceKeyvalues. The doc comment (DataSourceKey.cs:6-11) stresses thatNameis the physical source name produced by the Infrastructure resolver after collapsing logical names that share a connection string, so two logical names pointing at the same connection string end up with the same physical key (and are joinable), while genuinely distinct databases do not. - Walkthrough
- The positional record
DataSourceKey(DataSource Engine, string Name)(DataSourceKey.cs:15), parameters documented atDataSourceKey.cs:13-14. DefaultName(DataSourceKey.cs:18): theconst string"Default"reserved for the top-levelConnectionStringssection.Default(DataSource engine)(DataSourceKey.cs:23): a static factory building the default key for an engine.ToString()(DataSourceKey.cs:26): an override rendering"{Engine}/{Name}"for diagnostics.
- The positional record
- Why it's built this way: making the key a value type with structural equality reduces the routing decision
(same physical database, relational engine) to an equality comparison, and a host with no
DataSourcesconfiguration collapses everything ontoDefaultand behaves like a single-database monolith (ADR-006). - Where it's used:
EntityDataSourceRegistrymaps each entity type to a key andDataSourceResolverperforms the logical-to-physical collapse;IDataSourceServiceresolves and compares them;DbContextFactorycaches one context instance per key.
IDataSourceService
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IDataSourceService.cs:31· Level 2 · interface
- What it is: resolves which physical data source (
DataSourceKey: engine plus database) backs a given entity type, and determines whether two entity types support EF Core.Include()between them, all without the Application layer touching EF or Infrastructure. - Depends on:
DataSource(Level 0) andDataSourceKey(Level 1), both in the same namespace. - Concept introduced, multi-database routing exposed to the Application layer.
[Rubric §8, Data Architecture]assesses deliberate database-per-service design, explicit routing, and the absence of accidental cross-database JOINs. The layer must decide whether a navigation between two entities can use an EF.Include(), which is valid only when both entities live in the same physical database and that engine is relational. This interface answers that question without an EF reference, keeping Application pure (ADR-006). The doc comment names the consumer directly (IDataSourceService.cs:25-30):NavigationMetadataProvideruses it to classify navigation properties as supported or unsupported includes. - Walkthrough: six members across three concerns, every one of them synchronous, because the resolution is a
lookup against an eagerly built registry, not I/O.
GetDataSourceKey(Type entityType)(IDataSourceService.cs:36) andGetDataSourceKey(string entityFullName)(IDataSourceService.cs:41): resolve the physical key by CLR type or by full type name (the name overload exists because navigation metadata carries names, not resolved types).GetDataSource(string entityFullName)(IDataSourceService.cs:46) andGetDataSource(Type entityType)(IDataSourceService.cs:51): resolve just the engine.HaveIncludeSupport(DataSourceKey first, DataSourceKey second)(IDataSourceService.cs:61): the crux. The contract documented atIDataSourceService.cs:53-60is that it returnstrueonly when both keys identify the same physical database and the engine is relational, since Cosmos DB has no cross-document JOINs.HaveIncludeSupport(string firstEntityFullName, string secondEntityFullName)(IDataSourceService.cs:70): the same test by entity name, resolving each side's key first.
- Why it's built this way: ADR-006 replaces cross-service foreign keys with scalar columns and routes consistency through the outbox, so to build a query the Application layer must know the routing topology well enough to classify each navigation as include-able or manual-load-required. Exposing that as a narrow query interface (rather than handing Application the registry) keeps the collapse rules on the Infrastructure side.
- Where it's used: consumed by
NavigationMetadataProviderto drive the supported/unsupported include split, and indirectly by the query pipeline's eager-loading decisions. The Infrastructure implementation is a facade overEntityDataSourceRegistry.
IOutboxAdministration
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IOutboxAdministration.cs:16· Level 3 · interface
- What it is: the operator surface over the outbox tables a host owns: list the dead letters, replay them, republish a window of already-processed integration events, and count the pending backlog.
- Depends on:
Resultand its generic form (viaMMCA.Common.Shared.Abstractions,IOutboxAdministration.cs:1) andOutboxDeadLetter, the record declared in the same file (IOutboxAdministration.cs:122). - Concept introduced, a way BACK into delivery for an undelivered event.
[Rubric §13, Observability & Operability]assesses whether the system can be operated after something goes wrong, not just observed while it works. The interface doc puts the alternative plainly (IOutboxAdministration.cs:5-9): without this surface the only terminal states for a failed message are "eventually deleted by the retention sweep" and "edited by hand in production SQL".[Rubric §29, Resilience & Business Continuity]assesses recovery from partial failure, which is exactly what a replay is: the outbox (ADR-003) guarantees an event is recorded in the same transaction as its state change, and this interface is how a recorded-but-undelivered event gets another chance.[Rubric §9, API & Contract Design]shows up in the return type: every method returnsResult, because an unreachable source or an unknown source name is an expected failure an operator screen renders, not an exception (IOutboxAdministration.cs:10-14). - Walkthrough: four methods, each with an explicit (non-defaulted) cancellation token. Three of them take a
nullable
dataSourcefilter wherenullmeans "every source this host owns"; the republish always spans every source.ListDeadLettersAsync(string? dataSource, int skip, int take, CancellationToken cancellationToken)(IOutboxAdministration.cs:33-37): the read. Dead-lettered means unprocessed with a dead-letter stamp, and rows come back oldest first (IOutboxAdministration.cs:18-21) asOutboxDeadLetterrecords, paged byskip/take. The offset runs 0 to 10,000; a larger one is a validation failure, because each source returns up toskip + takerows for the in-memory merge (IOutboxAdministration.cs:26-29).ReplayDeadLettersAsync(string? dataSource, IReadOnlyCollection<Guid>? ids, CancellationToken cancellationToken)(IOutboxAdministration.cs:54-57): returns rows to the pending pool and answers with the number of rows moved. The doc comment (IOutboxAdministration.cs:39-44) pins the semantics: the dead-letter stamp and reason cleared,RetryCountback to zero and the claim lease cleared, so the next poll cycle picks the rows up, whileLastErroris deliberately KEPT (the reason a message failed is the first thing anyone asks after a replay) andOccurredOnis untouched, so a replayed row keeps its place in its ordering key. Anullor emptyidsreplays EVERY dead letter in the selected scope (IOutboxAdministration.cs:48-51), which is a wide operation stated as such.RepublishProcessedAsync(DateTime fromUtc, DateTime toUtc, CancellationToken cancellationToken)(IOutboxAdministration.cs:91-94): returns the INTEGRATION-event rows processed inside[fromUtc, toUtc)to the pending pool, across every source this host owns, so the processor publishes them again; the processed stamp, the retry count and the claim lease are cleared in one set-based update per source, whileLastErrorandOccurredOnare untouched (IOutboxAdministration.cs:60-64). It exists for a broker-side loss after a successful publish and for a transport cutover (IOutboxAdministration.cs:66-67). Delivery is at-least-once, so consumers absorb the duplicates through the inbox (ADR-021); domain-event rows are never reset, because their in-process handlers have no inbox and already ran. Without the consumer inbox (the in-process message bus, which wires none whateverMessageBus:EnableInboxsays, or a broker host that setMessageBus:EnableInbox=false) the call is refused withOutbox.RepublishRequiresInboxand nothing is touched (IOutboxAdministration.cs:70-73). The window is bounded by age as well as width: one that starts before the inbox horizon (Inbox:RetentionDays, default 30 days) is refused withOutbox.RepublishWindowPastInboxHorizon, because consumers dead-letter an event older than their horizon without running it. The check uses this host's horizon, which cannot prove anything about other hosts, so the doc comment asks forInbox:RetentionDaysto stay equal across the services of one application (IOutboxAdministration.cs:76-81). Both bounds must be UTC,fromUtcinside the horizon,toUtcafterfromUtc, and the window at most seven days wide (IOutboxAdministration.cs:84-87).CountPendingAsync(string? dataSource, CancellationToken cancellationToken)(IOutboxAdministration.cs:105): counts rows still awaiting dispatch. The doc comment draws the distinction that matters for operators (IOutboxAdministration.cs:96-101): unlike theoutbox.pending.depthgauge, which reports what the processor last observed (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxMetrics.cs:76), this counts the tables at the moment of the call and includes rows currently under a claim lease. "Pending" means unprocessed and not dead-lettered (IOutboxAdministration.cs:96), which is exactly the predicate the implementation counts (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxAdministration.cs:312).
- Why it's built this way: declaring the operator surface in Application means an admin endpoint, a support
command, or a scheduled job can drive it without referencing EF or the outbox entity, and the
Resultreturn keeps a bad source name on the same rails as any other user error. The retention sweep that would otherwise be a dead letter's only exit isOutboxCleanupService, whose own comment points atIOutboxAdministration.ReplayDeadLettersAsyncas the alternative (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxCleanupService.cs:177). - Where it's used: implemented by
OutboxAdministration(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxAdministration.cs:38-45), registered withTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:310-311), scoped because it creates one child scope per data source it visits and holds no state of its own (DependencyInjection.cs:308-309). The implementation caps one page at 500 rows so an admin call cannot ask for the whole table at once (OutboxAdministration.cs:48), bounds the offset asMaxSkip= 10,000 so one call cannot materialize a whole dead-letter table per source (OutboxAdministration.cs:50-55), rejects askipoutside 0 to 10,000 or atakeoutside 1 to 500 as validation errors (OutboxAdministration.cs:57-61,OutboxAdministration.cs:96-100), and expresses replay as one set-basedUPDATEper target that clearsDeadLetteredOnandDeadLetterReason, zeroesRetryCountand drops the lease (OutboxAdministration.cs:184-191) rather than as loaded entities. The republish reads the inbox switch and horizon from the injectedInboxPosture(OutboxAdministration.cs:86-87), which derives both fromMessageBusSettings.IsInboxEnabledandInbox:RetentionDays(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/InboxPosture.cs:18-25), refuses with a conflict error before validating anything else (OutboxAdministration.cs:75-78,OutboxAdministration.cs:232-233), enforces the seven-day cap asMaxRepublishWindow(OutboxAdministration.cs:64,OutboxAdministration.cs:327-336), refuses a window that starts before the horizon measured on the injectedTimeProvider, with no age bound when there is no horizon (OutboxAdministration.cs:80-83,OutboxAdministration.cs:338-349), resolves each source's DISTINCT stored event names and updates only those that resolve to an integration event (OutboxAdministration.cs:255-279), and logs every source, a zero included (OutboxAdministration.cs:283-286). - Caveats / not-in-source: the framework registers the service but ships no controller over it. No
MMCA.Common.APIendpoint and no ADC call site referencesListDeadLettersAsync,ReplayDeadLettersAsync,RepublishProcessedAsync, orCountPendingAsynctoday; outside the registration the only callers in Common are the Infrastructure tests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Outbox/Administration/OutboxAdministrationTests.cs). A host that wants an operator screen wires its own endpoint or command over the injected interface.
IEntityQuerier<TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:80· Level 4 · interface
- What it is: the set-returning half of the repository split: collection reads, projections, single-row and grouped aggregate reads, lookup pairs, counts, the specification-first block, and keyset paging. Fifteen members in all.
- Depends on:
AuditableBaseEntity<TIdentifierType>(theTEntityconstraint,IRepository.cs:81),BaseLookup<TIdentifierType>(the lookup projection, fromMMCA.Common.Shared.DTOs,IRepository.cs:5and:224),ISpecification<TEntity, TIdentifierType>(fromMMCA.Common.Domain.Interfaces,IRepository.cs:3, first used in a signature at:151),ResultwithKeysetPageRequestandKeysetCollectionResult<T>(fromMMCA.Common.Shared.Abstractions,IRepository.cs:4, used at:318-319), andSystem.Linq.Expressions(IRepository.cs:1). - Concept introduced, the ISP-split repository ladder.
[Rubric §1, SOLID]assesses whether clients depend only on the members they use.IRepository.csdefines a deliberate ladder of ever-wider interfaces so a handler declares exactly the surface it needs:IEntityReader(by-id lookups,IRepository.cs:21),IEntityQuerier(set-returning reads, this type,:80),IReadRepository(reader plus querier plus rawIQueryable,:332),IWriteRepository(mutations,:369), andIRepository(read plus write,:495). The doc comment says it outright (IRepository.cs:68-71): prefer this overIReadRepositorywhen a handler needsGetAllAsync,GetProjectedAsync, orCountAsync.[Rubric §12, Performance & Scalability]also applies: every member here exists so the database answers the question.GetProjectedAsync<TResult>takes anExpression<Func<TEntity, TResult>>translated to SQL,FirstOrDefaultAsyncreturns one row instead of a materialized set filtered in memory, andCountByAsync/SumByAsyncpush aGROUP BYdown instead of folding rows client-side. The querier is the rung that keeps growing: fifteen members against the reader's five, so "focused" here means reads that return sets or aggregates, not a small interface (ADR-055 and its Revision (2026-08-31), which records the five most recent additions). - Concept introduced,
ignoreQueryFiltersmeans soft-deleted rows and nothing else.[Rubric §11, Security]assesses whether a convenience flag can widen a security boundary. An interface-level<remarks>block (IRepository.cs:75-79) pins the contract: everyignoreQueryFiltersparameter here drops the namedSoftDeletefilter and leaves the namedTenantfilter applied, and the wording is repeated on each parameter that carries it (for exampleIRepository.cs:99-103and:126-130). That is enforced downstream, whereEFReadRepository<TEntity, TIdentifierType>passes a one-element filter-name array to EF's namedIgnoreQueryFiltersoverload (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:41, used at:52,:81,:102,:198,:288,:365,:379, and:445-446) rather than EF's parameterless form; its own comment (EFReadRepository.cs:38) spells out that dropping both would let a caller asking to see deleted rows silently read every tenant's data. The two named filters come fromApplicationDbContext(ApplicationDbContext.cs:712and:391). - Walkthrough
GetAllAsync(IEnumerable<string> includes, where?, orderBy?, select?, asTracking, ignoreQueryFilters, CancellationToken)(IRepository.cs:85-92): the general collection read with optional includes, filter, ordering, and same-type projection. Noteincludesis the one non-optional parameter, so a caller must state its eager-loading intent explicitly (pass[]for none).GetProjectedAsync<TResult>(select, where?, asTracking, ignoreQueryFilters, CancellationToken)(IRepository.cs:105-110): SQL-side projection to an arbitrary result type.FirstOrDefaultAsync(where, includes?, asTracking, ignoreQueryFilters, CancellationToken)(IRepository.cs:134-139): the single-row predicate read. The remarks (IRepository.cs:115-122) name the alternative it exists to remove,GetAllAsyncfollowed by an in-memoryFirstOrDefault, which materializes the whole matching set to keep one entity, and warn that no ordering is applied, so "first" is whatever the provider returns first.FirstOrDefaultAsync(ISpecification<TEntity, TIdentifierType> specification, CancellationToken)(IRepository.cs:150-152): the deterministic counterpart. Unlike the predicate overload it honors the specification's ORDERING, so "first" means what the specification says it means (IRepository.cs:141-145).CountByAsync<TKey>(keySelector, where?, CancellationToken)(IRepository.cs:169-173): aGROUP BYcount, returning one dictionary entry per key that has at least one row. The remarks (IRepository.cs:158-163) explain why the member has to exist at all: the Application layer references no EF Core, so a handler needing a grouped count has noIQueryableto group and would otherwise project every matching row out of the database and group client-side.TKeyis constrainednotnull(IRepository.cs:173).SumByAsync<TKey>(keySelector, sumSelector, where?, CancellationToken)(IRepository.cs:186-191): the groupedSUM, the counterpart ofCountByAsync(IRepository.cs:175-179).FindIncludingDeletedAsync(where, includes?, asTracking, CancellationToken)(IRepository.cs:217-221): the resurrection read (BR-135,IRepository.cs:199), returning a named tuple ofActiveandSoftDeletedmatches. The remarks (IRepository.cs:197-208) give the whole rationale: a create handler whose natural key already exists as a soft-deleted row must reactivate that row rather than insert a duplicate the unique index will reject, and it needs both halves of the answer in one round trip, since an active match is a conflict, a soft-deleted match is the row to bring back, and neither is a plain insert. TheasTrackingparameter carries its own warning (IRepository.cs:211-214): a caller intending to reactivate wantstrue, otherwise the reactivation saves nothing. See ADR-005 for the soft-delete policy this read serves.GetAllForLookupAsync(string nameProperty, where?, asTracking, CancellationToken)(IRepository.cs:224-228): returns lightweightBaseLookup<TIdentifierType>id/name pairs for dropdowns without materializing full entities. It has noignoreQueryFiltersparameter: a lookup list never offers deleted rows.CountAsync(CancellationToken)(IRepository.cs:231) andCountAsync(Expression<Func<TEntity, bool>> where, CancellationToken)(IRepository.cs:234-236): total and predicated counts.CountAsync(ISpecification<TEntity, TIdentifierType> specification, CancellationToken)(IRepository.cs:245-247): the specification-shaped count. The doc comment (IRepository.cs:238-241) states that ordering and paging on the specification are ignored deliberately, since a count of "page 3 of the matches" is never what a caller means.ListAsync(ISpecification<TEntity, TIdentifierType> specification, CancellationToken)(IRepository.cs:262-264): runs a specification and returns the matching entities. The remarks (IRepository.cs:252-258) draw the line between the two specification shapes: a plainISpecificationcontributes itsCriteriaonly, while aQuerySpecification<TEntity, TIdentifierType>also contributes includes, ordering, paging, tracking, and soft-delete scope, so one object describes the whole read instead of five loose arguments.ListAsync<TResult>(specification, Expression<Func<TEntity, TResult>> select, CancellationToken)(IRepository.cs:281-284): the projecting overload, so only the selected columns leave the database. The remarks (IRepository.cs:270-275) pin the ordering rule: the projection is applied after the specification's ordering and paging, so a paged specification still pages over entity rows and projects only that page, and includes on the specification are redundant here but not harmful.AnyAsync(ISpecification<TEntity, TIdentifierType> specification, CancellationToken)(IRepository.cs:293-295): existence by specification, with ordering and paging ignored for the same reason as the specificationCountAsync(IRepository.cs:287-288).GetPageByCursorAsync(KeysetPageRequest request, ISpecification<TEntity, TIdentifierType>? specification = null, CancellationToken)(IRepository.cs:318-321): one keyset ("seek") page plus the cursor for the next one, and the only member here that returns aResult, because an unknown sort column and a malformed cursor are caller errors rather than exceptions and must never come back as a silent first page (IRepository.cs:308-312). The remarks (IRepository.cs:301-313) state the trade in full: one index seek regardless of scroll depth and no skipped or repeated rows, against no random page access and no total count, with exactly one sort key supported andIdas the tie-break.
- Why it's built this way: splitting reads into a focused querier lets a handler signal its access pattern through its constructor dependency and keeps projection, aggregation, and counting off the by-id interface. Declaring the specification-first members here rather than on a separate interface is what keeps a handler that already depends on the querier from needing a second dependency to run a specification.
- Where it's used: query handlers needing collections, aggregates, specifications, or a keyset page; folded
into
IReadRepository<TEntity, TIdentifierType>(IRepository.cs:333) and implemented concretely byEFReadRepository<TEntity, TIdentifierType>(for exampleGetProjectedAsyncatEFReadRepository.cs:75,CountByAsyncat:127,SumByAsyncat:150, the projectingListAsyncat:464), withEFReadRepositoryDecorator<TEntity, TIdentifierType>wrapping every call in a MiniProfiler step (EFReadRepositoryDecorator.cs:17, and:45-83for the newer members). The mechanics behind the specification-first block are walked through later in this chapter rather than repeated here:SpecificationEvaluatorturns a specification into anIQueryable,KeysetQueryBuilderbuilds the ordering, the seek predicate, and the cursor encoding, andEFReadRepository<TEntity, TIdentifierType>owns the tracking and filter-scope policy those two are handed. - Caveats / not-in-source:
GetProjectedAsynccarriesignoreQueryFiltersbefore the cancellation token (IRepository.cs:109-110), so any caller or test double that passes arguments positionally has to account for it; the compiler catches positional callers, but a mock configured with a fixed argument count does not fail until run time. The twoFirstOrDefaultAsyncoverloads are public overloads that both carry optional parameters, which the RS0026 public-API analyzer rule forbids; each is annotated with a targeted[SuppressMessage("ApiDesign", "RS0026...")](IRepository.cs:133and:149) whose justification records them as grandfathered: released after the v1.152 baseline while RS0026/RS0027 were off, so changing either signature now would be a breaking change. A new overload on this interface does not inherit that exemption.
IEntityReader<TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:21· Level 4 · interface
- What it is: the by-id half of the repository split:
GetByIdAsync(two overloads),GetByIdsAsync, andExistsAsync(two overloads), for handlers whose data access is a point lookup. - Depends on:
AuditableBaseEntity<TIdentifierType>(theTEntityconstraint,IRepository.cs:22) andSystem.Linq.Expressionsfor the predicate overload (IRepository.cs:1). - Concept, minimal data access as a declared dependency.
[Rubric §1, SOLID](Interface Segregation, introduced onIEntityQuerier) and[Rubric §8, Data Architecture](deliberate, minimal access patterns). The doc comment is explicit (IRepository.cs:9-13): prefer this overIReadRepository<>when a handler only needsGetByIdAsyncorExistsAsync, because that signals minimal data access. This interface carries the same<remarks>contract as the querier (IRepository.cs:16-20):ignoreQueryFiltersmeans "include soft-deleted rows" and nothing more, with theTenantfilter left in force. It is also the rung that does not move: every round of specification and aggregate growth has landed on the querier, so the reader is still five members. - Walkthrough
GetByIdAsync(TIdentifierType id, CancellationToken)(IRepository.cs:26-28): plain fetch, returnsnullwhen missing.GetByIdAsync(TIdentifierType id, IEnumerable<string> includes, bool asTracking = false, CancellationToken)(IRepository.cs:31-35): the eager-load overload; include paths are navigation-property names.GetByIdsAsync(ids, includes?, asTracking, ignoreQueryFilters, CancellationToken)(IRepository.cs:48-53): a single-query bulk fetch that replaces an N+1 loop of point lookups. The doc comment warns it may return fewer entities than requested when some ids do not exist (IRepository.cs:47), so the caller must reconcile, and theignoreQueryFiltersparameter is documented in full (IRepository.cs:41-45) rather than by reference.ExistsAsync(TIdentifierType id, bool ignoreQueryFilters = false, CancellationToken)(IRepository.cs:56-59) andExistsAsync(Expression<Func<TEntity, bool>> where, bool ignoreQueryFilters = false, CancellationToken)(IRepository.cs:62-65): existence checks by key or by predicate. The flag is what lets a handler ask whether a soft-deleted row exists, for example to detect a conflict when re-creating a record that was deleted earlier.
- Why it's built this way: a handler that only needs a point lookup takes the narrowest interface, which reads clearly at the constructor and mocks in two lines in a test.
- Where it's used: command handlers that load an aggregate before mutating it; folded into
IReadRepository<TEntity, TIdentifierType>(IRepository.cs:333).
IReadRepository<TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:332· Level 5 · interface
What it is: the full read surface over an entity, combining
IEntityReader<TEntity, TIdentifierType>(by-id lookups) andIEntityQuerier<TEntity, TIdentifierType>(collections, projections, specifications, grouped aggregates, and keyset pages), and adding fourIQueryable<TEntity>properties for handlers that need raw LINQ plus oneQueryFormethod that hands back a specification's scoped, unordered, unpaged base query (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:332-364).Depends on:
IEntityReader<TEntity, TIdentifierType>andIEntityQuerier<TEntity, TIdentifierType>, both declared in the same file and both listed as base interfaces (IRepository.cs:333);AuditableBaseEntity<TIdentifierType>as theTEntityconstraint (IRepository.cs:334);ISpecification<TEntity, TIdentifierType>as theQueryForparameter (IRepository.cs:363). Externals: BCLIQueryable<T>only. No EF Core type appears anywhere in the declaration, which is what keeps this interface legal in the Application layer.Concept, the composition point of the ISP ladder, and controlled
IQueryableexposure.[Rubric §1, SOLID]assesses whether clients depend only on the members they use.IRepository.csdefines a ladder of ever-wider interfaces so a handler declares exactly the surface it needs:IEntityReader(five members,IRepository.cs:21),IEntityQuerier(fifteen members,IRepository.cs:80), this type (both of those plus four properties and one method, twenty-five members in total,IRepository.cs:332),IWriteRepository(IRepository.cs:385), andIRepository(read plus write,IRepository.cs:508). The doc comment records a migration stance rather than a ban (IRepository.cs:324-329): existing code should continue using this interface, and new handlers can depend on the focused sub-interfaces for better ISP compliance.[Rubric §12, Performance & Scalability]assesses whether expensive query behavior is a deliberate choice. The four properties turn EF's tracking mode and query-splitting mode into a named decision at the call site: asking forTableNoTrackingSplitQueryis visible in review, where a plainDbSetwould silently track every row and emit one cartesian join.Walkthrough: this interface's own body is four get-only
IQueryable<TEntity>properties and one method.Table(IRepository.cs:338): the base queryable with change tracking enabled, the shape a mutation path composes over. Implemented as the rawDbSet(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:524).TableNoTracking(IRepository.cs:341): the no-tracking queryable, documented as best for read-only queries and implemented asEntities.AsNoTracking()(EFReadRepository.cs:527).TableNoTrackingSingleQuery(IRepository.cs:344): no-tracking, pinned to a single SQL statement throughAsSingleQuery()(EFReadRepository.cs:530).TableNoTrackingSplitQuery(IRepository.cs:347): no-tracking in split-query mode, which avoids the cartesian explosion that collection includes cause, throughAsSplitQuery()(EFReadRepository.cs:533). It is the same concernIQueryableExecutoraddresses for callers that hold anIQueryablerather than a repository.QueryFor(ISpecification<TEntity, TIdentifierType> specification)(IRepository.cs:363): returns the base queryable a specification scopes, for a caller that composes its own ordering and paging on top. The remarks (IRepository.cs:353-360) fix the contract: it applies the criteria, the soft-delete scope (WithSoftDeleteddrops the named soft-delete filter only, so the tenant filter stays in force), the includes and tracking, and deliberately does NOT apply the specification's ordering or Skip/Take, because paging inside the returned query would make any count or page composed on top of it describe the wrong set;ListAsync(specification)stays the call that applies the whole shape.EFReadRepositoryimplements it by picking a tracked or untracked base (dropping only the soft-delete filter when asked,EFReadRepository.cs:573-582), runningSpecificationEvaluatorwithapplyShape: false, and then applying aQuerySpecification's include paths (EFReadRepository.cs:585-596); the profiling decorator passes it straight through (EFReadRepositoryDecorator.cs:164).- The twenty inherited members come from the two base interfaces and are walked through on their own sections: five point-lookup members on
IEntityReader, fifteen set-returning members onIEntityQuerier.
Why it's built this way: the framework needed one interface a query handler can take when it genuinely uses the whole read surface, without forcing every handler to take it. Keeping the composition free of new methods means the two halves stay independently declarable and independently mockable, and it gives the profiling decorator one surface to wrap. Naming the four queryables separately, rather than exposing a
DbSet, is what makes tracking and split-query opt-in rather than accidental. The ladder itself is ADR-055.Where it's used: obtained through
IUnitOfWork.GetReadRepository<TEntity, TIdentifierType>()(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IUnitOfWork.cs:29), which is the sanctioned way to get one; implemented byEFReadRepository<TEntity, TIdentifierType>(EFReadRepository.cs:21-25) and wrapped inEFReadRepositoryDecorator<TEntity, TIdentifierType>(EFReadRepositoryDecorator.cs:17) byRepositoryFactoryonly when MiniProfiler is enabled (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:55-63).EntityQueryService<TEntity, TEntityDTO, TIdentifierType>derives itsRepositoryproperty from the unit of work at construction (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:91), and its list and specification by-id reads take their base query fromQueryFor(through a tracked view of the specification when the request asks for tracking and the specification did not), so the request's own sort and page apply on top (EntityQueryService.cs:368-372,EntityQueryService.cs:727-737).- Caveats / not-in-source: a mutation path must not compose its query offTableNoTrackingand then expect the save to persist, because one no-tracking source makes the whole composed query untracked. That constraint is not stated in this file; it follows from EF's tracking semantics.
IWriteRepository<TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:385· Level 5 · interface
What it is: the write half of the repository abstraction, over an aggregate root:
AddAsync,AddRangeAsync, twoSetOriginalRowVersionoverloads,TouchConcurrencyToken,ExecuteDeleteAsync, andExecuteUpdateAsync(IRepository.cs:385-495). Seven members, and not one of them saves. There is no update-marking member either: a change to an aggregate the scope already tracks is picked up by the change tracker when the unit of work saves.Depends on:
AuditableAggregateRootEntity<TIdentifierType>as theTEntityconstraint (IRepository.cs:386),IRowVersionedfor the child-concurrency overload (written by its qualifiedDomain.Interfaces.IRowVersionedname,IRepository.cs:423), andIUpdatePropertySetter<TEntity>for the set-based update builder (IRepository.cs:493). Externals:System.Linq.Expressions(IRepository.cs:1).Concept introduced, writes enter through the aggregate root, and the repository never flushes.
[Rubric §4, DDD]assesses whether the aggregate boundary is an enforced rule rather than a naming convention. The constraint here is the narrowerAuditableAggregateRootEntity<TIdentifierType>, not theAuditableBaseEntity<TIdentifierType>the read side accepts, and the doc comment says exactly why (IRepository.cs:369-376): a write enters the aggregate through its root so that the root's invariants are enforced and its domain events are collected, and a repository over a child entity would let a caller persist a change the root never saw. Reading a child directly stays harmless and stays supported throughIReadRepository<TEntity, TIdentifierType>. The rule is enforced by the compiler, not by review: asking for a write repository over a child entity does not compile.[Rubric §8, Data Architecture]assesses whether persistence is deliberate: one save boundary, one concurrency story. This interface has noSaveand noSaveChangesAsync. The doc comment states the division (IRepository.cs:377-381): the repository stages changes and never flushes them, because persisting is the unit of work's job, so every repository touched in a scope is written as one unit under one audit stamp. A handler that mutates through a repository and then forgetsIUnitOfWork.SaveChangesAsynchas written nothing.Concept introduced, optimistic-concurrency wiring and change-tracking-bypass writes. Five members carry the weight.
SetOriginalRowVersion(TEntity entity, byte[] rowVersion)(IRepository.cs:412): plants the client's last-observedRowVersionas the tracked entity's original concurrency token, so the next save emits itsWHERE RowVersion = @originaland raisesDbUpdateConcurrencyExceptionwhen the row moved since the client read it (IRepository.cs:405-409). The token only ever arrives throughIf-Match, so[SupportsIfMatch]answers that exception as412 Precondition Failed, and the doc comment itself names that status and the attribute (IRepository.cs:407-408; the child overload's comment likewise promises "the same stale-token 412 protection",IRepository.cs:417) (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:179-189, ADR-035). The implementation setsOriginalValueon the tracked entry'sRowVersionproperty and rejects a null token outright (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:50-59).SetOriginalRowVersion(Domain.Interfaces.IRowVersioned childEntity, byte[] rowVersion)(IRepository.cs:423): the same protection for a tracked child of the aggregate, for example aProductVariantunder aProduct. The doc comment explains why a second overload exists at all (IRepository.cs:414-420): the repository'sTEntityis the root, so the typed overload cannot reach children, and this one accepts anyIRowVersionedentity instead (ADR-035). It reaches the entry through an(object)cast (EFRepository.cs:61-70).TouchConcurrencyToken(TEntity entity)(IRepository.cs:446): forces the aggregate ROOT to take part in the next save when a conditional write left it untouched, so the precondition the caller sent is actually evaluated (SEC-Common-77). The remarks explain the gap it closes (IRepository.cs:430-445):SetOriginalRowVersiononly stamps the tracked entry's ORIGINAL value, it does not make the entry dirty, so an applier that changes only child rows leaves the rootUnchanged, EF emits no rootUPDATE, noWHERE RowVersion = @tokenreaches the database, and the stale-token check silently does not fire, letting two administrators editing different children of the same aggregate from the same ETag both get200while the second silently discards the first's edit. Touching the root restores the412ADR-035 promises. It has no default body, so every implementer must provide it: a repository or test double that silently skipped the touch would lose the412instead of failing to compile, and an in-memory double with no concurrency token implements it as a no-op (IRepository.cs:441-443,:446).EFRepository<TEntity, TIdentifierType>implements it by markingLastModifiedOnmodified on anUnchangedroot only, so the audit interceptor fills in the value and EF appends theRowVersionpredicate; a root that is already modified, deleted, or detached is left alone (EFRepository.cs:72-90).ExecuteDeleteAsync(Expression<Func<TEntity, bool>> where, CancellationToken)(IRepository.cs:464-466): a set-based delete run directly in the database, one statement, no change tracker. The doc comment warns in capitals that it does not trigger domain events, audit stamps, or soft delete, and writes no field-level audit trail (noAuditTrailEntryrows for anIAuditedEntity, because the trail is produced only by the save pipeline), and that it is for maintenance scenarios only (IRepository.cs:448-453). There is deliberately no guard against an auditable or audited entity, unlike the retention helperBatchedDelete, which refuses one: erasing derived rows the caller is about to rewrite (a recomputed score, say) is a legitimate use, so the caller owns that decision and must not point it at user data that carries an audit, restore, or erasure obligation (IRepository.cs:454-459). The implementation is a one-liner over theDbSet(EFRepository.cs:93-99).ExecuteUpdateAsync(where, Action<IUpdatePropertySetter<TEntity>> setProperties, CancellationToken)(IRepository.cs:491-494): a set-basedUPDATE ... SET ... WHERE ...as one atomic statement.[Rubric §12, Performance & Scalability]applies alongside §8 here, and the long doc comment (IRepository.cs:468-490) is the teaching text for contention-proof conditional updates: guard the update insidewhere(the worked example is a stock decrement guarded byAvailableQuantity >= @qty), and then zero rows affected means the guard did not hold, so two racing callers can never both win and no rowversion retry loop is needed, because the database itself arbitrates. It also draws the exact boundaries: domain events and the field-level audit trail (noAuditTrailEntryrows for anIAuditedEntity) are bypassed (IRepository.cs:476-478), global query filters (soft delete) DO apply towhere, audit stamp fields are NOT bypassed, and the statement runs on the ambient transaction when one is active, so a decrement rolls back with its caller. The audit guarantee is not something the database does; it is compensation code in the implementation, which stampsLastModifiedOnfrom the injectedTimeProviderandLastModifiedByfromICurrentUserService(the default sentinel when there is no current user) unless the caller assigned them explicitly, rejects an empty setter list, and, on an engine with an application-stamped row version (PostgreSQL, SQLite,RowVersionStrategy.ClientStamped), re-stampsRowVersionwith a fresh GUID unless the caller set it, so a client still holding the pre-update token gets a concurrency conflict instead of passing itsIf-Matchcheck (SQL Server'srowversionmoves by itself;IRepository.cs:479-482,EFRepository.cs:131,:136-150) (EFRepository.cs:102-134, with theTimeProviderand the optionalICurrentUserServiceconstructor parameters atEFRepository.cs:27-31).
Walkthrough: the seven members in teaching order.
AddAsync(TEntity entity, CancellationToken)(IRepository.cs:393-395) andAddRangeAsync(IEnumerable<TEntity> entities, CancellationToken)(IRepository.cs:401-403): single and batch inserts, staged on the change tracker (EFRepository.cs:36-47). They are the only staging members; modifying an existing aggregate needs no repository call at all.- The two
SetOriginalRowVersionoverloads (IRepository.cs:412,:423),TouchConcurrencyToken(IRepository.cs:446), and the two database-side operations (IRepository.cs:464,:491) described above.
Why it's built this way: keeping writes in a focused interface means a query handler cannot accidentally acquire mutation methods, and the concurrency and set-based escape hatches are declared where a reader meets their warnings rather than buried in a concrete class. Constraining
TEntityto the aggregate root mirrors the constraint onIUnitOfWork.GetRepository(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IUnitOfWork.cs:20), which is how a handler is meant to obtain one, so the two agree by construction. LeavingSaveoff the interface entirely is what makes the single save boundary of ADR-006 enforceable: with several physical databases in one host, "save" cannot mean "save this repository".Where it's used: command handlers that mutate aggregates, always through
IUnitOfWork.GetRepository<TEntity, TIdentifierType>()(IUnitOfWork.cs:19); folded intoIRepository<TEntity, TIdentifierType>(IRepository.cs:508); implemented byEFRepository<TEntity, TIdentifierType>(EFRepository.cs:27-33), which derives fromEFReadRepository<TEntity, TIdentifierType>and adds only the write surface, and is wrapped inEFRepositoryDecorator<TEntity, TIdentifierType>when MiniProfiler is on (RepositoryFactory.cs:31-41). Both apps exercise the specialized members: in MMCA.Store,ChangeVariantPriceHandlercalls the child-typedSetOriginalRowVersionso a race on one product variant conflicts even when the product row itself is untouched (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Products/UseCases/ChangeVariantPrice/ChangeVariantPriceHandler.cs:48, with the same pattern inChangeVariantSkuHandler.cs:72); in MMCA.ADC,SessionScoringRunnerusesExecuteDeleteAsyncto clear a session's previous AI scores before re-adding them (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/DecisionSupport/ScoreEventSessions/SessionScoringRunner.cs:164,:170).Caveats / not-in-source:
ExecuteDeleteAsyncandExecuteUpdateAsyncbypass the domain-event capture thatDomainEventSaveChangesInterceptorperforms on save, so anything downstream that reacts to an event will not observe those writes. The interface says so in its doc comments; nothing in the type system stops it, so it stays a review rule rather than a compiler rule.
IRepository<TEntity, TIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:508· Level 6 · interface
- What it is: the combined read-write repository over an aggregate root, extending both
IReadRepository<TEntity, TIdentifierType>andIWriteRepository<TEntity, TIdentifierType>, so a command handler that reads an aggregate and then mutates it takes a single dependency (IRepository.cs:508). - Depends on:
IReadRepository<TEntity, TIdentifierType>andIWriteRepository<TEntity, TIdentifierType>, both named as bases onIRepository.cs:508, andAuditableAggregateRootEntity<TIdentifierType>as theTEntityconstraint (IRepository.cs:509). - Concept, the top of the ISP ladder, and where the aggregate-root constraint wins.
[Rubric §1, SOLID]and[Rubric §4, DDD]. The interface is purely compositional: it declares no members of its own, only two base interfaces and two constraints (IRepository.cs:508-510). What matters is which constraint survives the composition. The read side accepts anyAuditableBaseEntity<TIdentifierType>(IRepository.cs:334) and the write side only aggregate roots (IRepository.cs:386), so the combination inherits the narrower bound, and the doc comment states the consequence for the reader (IRepository.cs:500-504): a handler that only reads, and reads a child entity, depends onIReadRepositoryinstead, which still accepts any auditable entity. - Walkthrough: no members. The declaration is a semicolon-terminated interface with two bases and two generic constraints (
IRepository.cs:508-510), the C# shorthand for an empty body. Everything a caller can do through it is walked through on the two base sections, and beneath them onIEntityReaderandIEntityQuerier. - Why it's built this way: keeping the combined interface empty means the read and write surfaces each stay independently usable and independently mockable, while a handler that genuinely needs both still takes one constructor parameter. Composition rather than a fresh member list is also what keeps the ladder honest: there is exactly one definition of "read" and one of "write" in the codebase, and the widest rung is a deliberate choice a reviewer can see at the constructor rather than a default.
- Where it's used: obtained through
IUnitOfWork.GetRepository<TEntity, TIdentifierType>()(IUnitOfWork.cs:19-21), which is the sanctioned way to get one; implemented byEFRepository<TEntity, TIdentifierType>(EFRepository.cs:27-33) and produced, optionally wrapped for profiling, byRepositoryFactory(RepositoryFactory.cs:26-42).UnitOfWorkcaches the instance per closed generic interface type, sotypeof(IRepository<Order, int>)is the cache key for a whole scope (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:52,:43). - Caveats / not-in-source:
AddInfrastructuredoes register the open genericIRepository<,>againstEFRepository<,>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:130), which makes constructor-injectingIRepository<,>look supported. It is not the intended path:EFRepository<TEntity, TIdentifierType>takes a bareDbContextconstructor parameter (EFRepository.cs:27-28) and that registration file adds noDbContextservice, so a direct injection sidesteps both the data-source resolution and the per-scope repository cache thatGetRepositoryperforms (UnitOfWork.cs:52-60). Ask the unit of work.
IUnitOfWork
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IUnitOfWork.cs:10· Level 7 · interface
What it is: the one coordination point a handler uses to touch the database. It hands out typed repositories (read-write for aggregate roots, read-only for any entity), persists everything pending in one call, and exposes controlled transaction and explicit-key-insert operations. The doc comment states the contract in two sentences (
IUnitOfWork.cs:5-9): it coordinates persistence across multiple repositories within a single database context, andSaveChangesAsyncpersists all pending changes and dispatches domain events raised by tracked aggregates.Depends on:
AuditableAggregateRootEntity<TIdentifierType>andAuditableBaseEntity<TIdentifierType>as the two constraint bounds (IUnitOfWork.cs:1,:20,:30);IRepository<TEntity, TIdentifierType>andIReadRepository<TEntity, TIdentifierType>as the two return types (IUnitOfWork.cs:19and:29). Externals: BCLIDisposableandIAsyncDisposable, both declared as base interfaces (IUnitOfWork.cs:10). Notably absent: anything fromMicrosoft.EntityFrameworkCore, which is the point of the type.Concept introduced, the Unit of Work as the Application layer's only persistence verb.
[Rubric §8, Data Architecture]assesses whether persistence is deliberate: one save boundary, one transaction story, explicit concurrency and audit handling rather than scatteredSaveChangescalls. A unit of work is the scope inside which a caller sees a consistent view of the data and inside which all of its changes either land together or not at all. Here that scope is the DI scope:UnitOfWorkis registeredTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:132), it caches one repository per closed generic interface type (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:34,:37-45), and every repository it hands out is bound to a context obtained from the sameIDbContextFactory(UnitOfWork.cs:56), so two handlers in one request share one change tracker instead of racing two.[Rubric §3, Clean Architecture]assesses whether the inner layers declare intent while the outer layers own the technology. This interface lives inMMCA.Common.Applicationand names no EF type, which is exactly what lets the architecture fitness rule "Application must not depend on EF Core, use IRepository/IUnitOfWork" hold (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Layering/ArchitectureRules.Purity.cs:51-60). The EF-shaped work (a context per physical source, execution strategies, the engine-specific explicit-key insert SQL) sits behind it inMMCA.Common.Infrastructure.[Rubric §6, CQRS & Event-Driven]assesses whether events are raised and delivered from a single, reliable place.SaveChangesAsyncis that place: the doc comment (IUnitOfWork.cs:7-8) ties persistence and domain-event dispatch into one operation, and the mechanism behind it is the interceptor plus outbox flow described onDomainEventSaveChangesInterceptor.[Rubric §14, Testability]assesses whether the abstraction a handler depends on can be replaced without infrastructure. Because a handler asks this interface for its repositories rather than receiving them, oneMock<IUnitOfWork>substitutes the entire data layer; the framework ships that scaffold asHandlerTestBase<THandler>, which pre-stubsSaveChangesAsyncto return 1 (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Support/HandlerTestBase.cs:42) and wires each registered repository mock into bothGetRepositoryandGetReadRepository(HandlerTestBase.cs:61-62).Walkthrough: five members, in three groups.
GetRepository<TEntity, TIdentifierType>()(IUnitOfWork.cs:19-21): the read-write repository. Its constraint iswhere TEntity : AuditableAggregateRootEntity<TIdentifierType>(IUnitOfWork.cs:20), so the DDD rule that the doc comment states in prose ("Only aggregate roots can be directly persisted",IUnitOfWork.cs:14) is enforced by the compiler. In the implementation the call resolves the entity's physical data source throughIDataSourceService, fetches the matching context, builds the repository throughIRepositoryFactory, and caches it under the closed interface type (UnitOfWork.cs:52-60).GetReadRepository<TEntity, TIdentifierType>()(IUnitOfWork.cs:29-31): the read-only repository, constrained only toAuditableBaseEntity<TIdentifierType>(IUnitOfWork.cs:30), so child entities are readable even though they are not independently writable. Same resolution path, different factory method (UnitOfWork.cs:72-80).SaveChangesAsync(CancellationToken cancellationToken = default)(IUnitOfWork.cs:36): persists everything and returns the number of state entries written (IUnitOfWork.cs:35). The implementation is a straight delegation (UnitOfWork.cs:84-85) toDbContextFactory, which saves every cached context, not just one: it snapshots the contexts and loops in bounded passes (three,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:64) so a context materialized by a domain event handler mid-save is still saved (DbContextFactory.cs:285-299), then throws if any tracked change is left behind rather than losing it silently (DbContextFactory.cs:307-318).RequestExplicitKeyInsert()(IUnitOfWork.cs:45): a one-shot flag saying the next save may insert rows that carry explicit values for store-generated keys, for example rows imported from an external system with their source ids intact (IUnitOfWork.cs:38-44). The contract is engine-neutral: on an engine that refuses such a value unless it is switched on per table, the save pipeline does that around those inserts, and on every other engine the save runs unchanged (IUnitOfWork.cs:41-42). The implementation sets a boolean (UnitOfWork.cs:88,DbContextFactory.cs:324); the nextSaveChangesAsyncreads and immediately clears it (DbContextFactory.cs:275-276, which is what "automatically cleared after the save completes" means) and, for a context whose engine exposes anIExplicitKeyInsertDialectthroughIDataSourceEngine.ExplicitKeyInsert(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/IDataSourceEngine.cs:119), routes the save throughSaveWithExplicitKeyInsertAsync(DbContextFactory.cs:295-297). OnlySQLServerDataSourceEnginesupplies a dialect (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:49, theSET IDENTITY_INSERT ON/OFFtoggle perDbContextFactory.cs:266-269); the SQLite, PostgreSQL and Cosmos engines returnnull, so their save is the plain one. With a dialect, the save asks it for the affected entries grouped by table asExplicitKeyInsertGroupvalues (DbContextFactory.cs:337), pins one open connection for the whole save because the toggle is session state (DbContextFactory.cs:351-361, closed again at:364-368), and saves each group in its own round with the toggle on, because SQL Server allows only one table per session to have it on (DbContextFactory.cs:326-331,SaveExplicitKeyGroupsAsyncat:377).ExecuteInTransactionAsync<TResult>(Func<CancellationToken, Task<TResult>> operation, CancellationToken cancellationToken = default)(IUnitOfWork.cs:63-65): the interface's only transaction-control member; the manualSave(),BeginTransaction(),CommitTransaction(), andRollbackTransaction()members it used to sit alongside are gone from the interface. Its doc comment (IUnitOfWork.cs:47-59) states the reason: the operation runs wrapped by the active execution strategy, so a retrying strategy such asSqlServerRetryingExecutionStrategycan retry the whole transaction as one retriable unit, committing on success and rolling back before an exception propagates. The same comment carries the save rule (IUnitOfWork.cs:53-58): the commit does not save the operation's work, so the operation must save before it returns; the one exception is an internal-command row scheduled after the last save, which is saved just before the commit, and any other change still tracked at that point throwsInvalidOperationExceptionand rolls the unit back rather than being silently discarded. The implementation adds six behaviors worth knowing (DbContextFactory.cs:579-624, with the attempt runner at:589-647): a nested call joins the ambient transaction instead of opening a second one (DbContextFactory.cs:590-591); a returned failedResultrolls back exactly like an exception (DbContextFactory.cs:643-650); before committing,FlushEnrolledCommandsBeforeCommitAsync(DbContextFactory.cs:653,:659-685) saves the unit when every pending entry is an addedInternalCommandMessageand otherwise throws the unsaved-changes exception (DbContextFactory.cs:726-740); each retry starts from a reset change tracker, so entities a failed attempt added are not inserted twice (DbContextFactory.cs:608-609,ResetForRetryat:814-821); deferred in-process domain events are flushed only after a successful commit (DbContextFactory.cs:664-671); and a failure of the commit itself is never retried, surfacing asTransactionCommitAmbiguousExceptionthrown outside the strategy instead (DbContextFactory.cs:616-621).- The two base interfaces (
IUnitOfWork.cs:10) matter at scope teardown:UnitOfWorkforwards both disposal paths to the context factory (UnitOfWork.cs:96-122), so the async path awaits_dbContextFactory.DisposeAsync()(UnitOfWork.cs:106) rather than blocking.
Why it's built this way: under ADR-006 a single host may own several physical databases, so "save" cannot mean "call SaveChanges on the one context". Splitting the responsibility keeps that manageable:
IDbContextFactoryowns multi-source routing, saving, transactions and disposal, whileIUnitOfWorkis the narrow per-scope facade the Application layer is allowed to see, adding only repository resolution and caching on top (UnitOfWork.cs:13,:23). ExposingExecuteInTransactionAsyncas the interface's only transaction-control member, rather than the manualBeginTransaction/CommitTransaction/RollbackTransaction/Saveset it replaced, is what makes the ADR-014 pipeline's transaction rules enforceable in one place: business failures roll back and post-commit event dispatch is deferred. Keeping the interface in Application rather than Infrastructure is the ADR-013 and Clean Architecture pairing, since a handler returns aResultand never sees an EF type on the way there.Where it's used: injected into command handlers across the framework and both apps. In MMCA.Common:
TransactionalCommandDecorator<TCommand, TResult>takes it in its primary constructor (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/TransactionalCommandDecorator.cs:24) and callsExecuteInTransactionAsyncfor any command markedITransactional(TransactionalCommandDecorator.cs:33);DeleteEntityHandler<TEntity, TIdentifierType>takes it and resolves its write repository from it (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/DeleteEntityHandler.cs:37,:70);EntityQueryService<TEntity, TEntityDTO, TIdentifierType>both holds it and derives its read repository from it (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:34,:43,:87). In MMCA.ADC,RefreshFromSessionizeHandleris the live consumer of the explicit-key insert path, callingRequestExplicitKeyInsert()immediately before the save because Sessionize imports preserve external ids into tables with store-generated keys (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/RefreshFromSessionize/RefreshFromSessionizeHandler.cs:213-214). The single implementation isUnitOfWork(UnitOfWork.cs:13), which isinternal sealed, so consumers only ever see this interface.Caveats / not-in-source:
ExecuteInTransactionAsyncis not a distributed transaction: with several physical sources each gets its own transaction and commits are sequential and best effort, so a commit failure on the second source leaves the first already committed. The doc comment names that limitation and records that the thrownTransactionCommitAmbiguousExceptionnames each source's outcome (committed, ambiguous, or rolled back) so the partial state is observable rather than inferred, and that the caller's replay is what reconciles it (DbContextFactory.cs:567-577). A witness row that would let a replay learn what landed is deliberately not built, since a single transactional source needs none (DbContextFactory.cs:573-576); the outbox delivers whatever the commit did make durable (DbContextFactory.cs:564-565).
BlobNames
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Storage·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/BlobNames.cs:10· Level 0 · class (public static)
- What it is: a dependency-free static helper that reduces a user-supplied file name to a blob-safe
segment built only from
A-Z a-z 0-9 . _ -(BlobNames.cs:33-119). - Depends on: nothing first-party; BCL
StringBuilder. - Concept introduced, file-name sanitization as an upload trust boundary.
[Rubric §11, Security]assesses whether untrusted input (here, a caller-chosen file name that becomes part of a storage path and later aContent-Dispositionheader) is normalized before use rather than passed through. This is the naming half of the document-upload path;DocumentContentSnifferandFileUploadOptionsare its companions, mirroring howImageContentSnifferandIImageProcessorpair up for avatars. - Walkthrough: one public method plus three private helpers.
SanitizeFileName(string fileName, int maxLength = 100)(BlobNames.cs:33-74): trims trailing separators, splits the last.into stem and extension, falls back to the literalfilewhen nothing safe survives, lower-cases the extension, and truncates the stem so the whole result fitsmaxLength; the extension itself is never sacrificed, so a result can exceedmaxLengthonly when the extension alone is longer than the budget.KeepSafeCharacters(string fileName)(BlobNames.cs:80-102): rewrites the name over the safe alphabet (tested by the privateIsSafe,BlobNames.cs:118-119), collapsing any run of unsafe characters to one-and any run of dots to one..ToLowerAscii(string value)(BlobNames.cs:108-116): a hand-rolled ASCII lower-case so the result is independent of the host's culture.
- Why it's built this way: collapsing runs rather than dropping characters one-by-one keeps a long
run of spaces or path separators from producing a long run of dashes, and preserving the extension
unconditionally keeps a sanitized name usable by whatever later code inspects it (for example
DocumentContentSniffer, which reads only the extension). - Where it's used:
UploadSessionAssetHandlersanitizes the caller's file name before building the blob name (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/UploadFile/UploadSessionAssetHandler.cs:1). It has its own dedicated unit-test class (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/BlobNamesTests.cs).
DocumentFormats
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Storage·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/DocumentContentSniffer.cs:9· Level 0 · enum
- What it is: a
[Flags]-shaped enum of the document formatsDocumentContentSniffercan recognize:None,Pdf,Presentation,WordDocument,Spreadsheet, a combinedOfficeOpenXml,Zip,PlainText,Markdown, and a combinedAll(DocumentContentSniffer.cs:155-186). - Depends on: nothing; it is a plain BCL enum with bitwise-combinable members.
- Concept introduced: none on its own; it is the vocabulary
DocumentContentSniffer.Detectuses to let a caller declare which formats it accepts and to report which one it found. - Walkthrough:
OfficeOpenXmlis the bitwise-or ofPresentation | WordDocument | Spreadsheet, andAllis the bitwise-or of every leaf value; both let a caller pass one flag to accept a whole family instead of enumerating members. - Why it's built this way:
[Flags]lets a caller such as the session-asset upload path accept exactly the subset it wants (for example documents and zips but not plain text) with a single value. - Where it's used: the
allowedparameter of bothDocumentContentSniffer.Detectoverloads; passed byUploadSessionAssetHandlerandUploadSessionAssetCommandValidator(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/UploadFile/UploadSessionAssetCommandValidator.cs:1).
FileUploadOptions
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Storage·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/FileUploadOptions.cs:13· Level 0 · record (sealed)
- What it is: an immutable options record carrying the response headers a blob upload should be
stored with,
ContentDispositionandCacheControl(FileUploadOptions.cs:28-34), plus factory methods that build a correctly-encodedContent-Dispositionfrom a user-facing file name. - Depends on: nothing first-party; BCL
StringBuilder,Encoding.UTF8. - Concept introduced, RFC 6266/5987-correct
Content-Dispositionencoding.[Rubric §8, Data Architecture]assesses whether a storage-layer concern (here, the HTTP headers a blob is served with) is centralized in one place rather than hand-built at each call site. The staticNoneinstance (FileUploadOptions.cs:21) sets no headers, so a caller only reaches forAttachment/Inlinewhen it actually wants a download disposition. - Walkthrough: two public factory methods and three private helpers.
Attachment(string fileName, string? cacheControl = null)(FileUploadOptions.cs:48-49): builds anattachmentdisposition, so the browser downloads the blob underfileNameinstead of rendering it.Inline(string fileName, string? cacheControl = null)(FileUploadOptions.cs:59-60): builds aninlinedisposition, so the browser renders the blob when it can and otherwise downloads it underfileName.ForDisposition(string dispositionType, string fileName, string? cacheControl)(FileUploadOptions.cs:62-85): trims the name (falling back tofilewhen blank), then emits both an ASCIIfilename="..."fallback and a percent-encoded UTF-8filename*=UTF-8''...parameter in the same header, per RFC 6266.ToAsciiFallback(string fileName)(FileUploadOptions.cs:91-106) andToRfc5987(string fileName)(FileUploadOptions.cs:112-129): the two encodings behind the header; the ASCII fallback drops quotes, backslashes, semicolons and line breaks and replaces the rest of non-printable-ASCII with_, while the RFC 5987 form percent-encodes every UTF-8 byte outside theattr-charalphabet (FileUploadOptions.cs:135-139).
- Why it's built this way: emitting both an ASCII fallback and the UTF-8
filename*parameter in one header lets older clients that ignorefilename*still get a usable name, while modern clients get the exact, non-ASCII-safe original; centralizing the encoding here keepsIFileStorageServiceimplementations from having to get RFC 5987 right themselves. - Where it's used: the
optionsparameter ofIFileStorageService's document-upload overload (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/IFileStorageService.cs:41), implemented byAzureBlobFileStorageServiceandNullFileStorageService; called byUploadSessionAssetHandlerto attach a download name to an uploaded document.
ImageContentSniffer
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Storage·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/ImageContentSniffer.cs:9· Level 0 · class (public static)
- What it is: a dependency-free static helper that decides whether uploaded bytes are a JPEG, PNG, or WebP image by inspecting the leading magic bytes, never the client-declared content type or file extension.
- Depends on: nothing first-party (BCL
ReadOnlySpan<byte>; the file has nousingdirectives). It is the upload-side companion toIImageProcessor. - Concept introduced, magic-byte content sniffing as an upload trust boundary.
[Rubric §11, Security]assesses whether untrusted input is validated by its actual content rather than by a spoofable client-supplied MIME type or file extension; this type is the framework's answer for binary uploads.[Rubric §26, Front-End Security]also applies at the origin of an avatar upload, because the browser-suppliedContent-Typeis exactly what this code refuses to trust. The doc comment (ImageContentSniffer.cs:3-8) frames the division of labor under ADR-045: the sniffer narrows accepted inputs to jpeg/png/webp, then the caller hands content to the processor whose re-encoding keeps only pixels, while app-specific size limits and error codes stay in the calling handler. - Walkthrough: four span-based predicates, all expression-bodied and all
public.IsAllowedImage(ReadOnlySpan<byte> content)(ImageContentSniffer.cs:14-15): the entry point, a short-circuitingIsJpeg || IsPng || IsWebP.IsJpeg(ImageContentSniffer.cs:20-21): length at least 3 and the SOI prefixFF D8 FFchecked byte by byte.IsPng(ImageContentSniffer.cs:26-27): length at least 8 and aSequenceEqualagainst the exact 8-byte PNG signature89 50 4E 47 0D 0A 1A 0A.IsWebP(ImageContentSniffer.cs:32-35): length at least 12, aRIFFcontainer (bytes 0-3 against the UTF-8 literal"RIFF"u8) declaring theWEBPform type (bytes 8-11 against"WEBP"u8). Bytes 4-7 are the RIFF chunk size and are deliberately not inspected.
- Why it's built this way:
ReadOnlySpan<byte>plus UTF-8 literals mean the checks allocate nothing and run directly on the payload prefix, and being a pure static class it is callable from any layer without DI or mocking. Checking bytes rather than the declared type is the security point: a client can renameevil.exetoavatar.png, but it cannot forge a valid leading signature and still survive the re-encode that follows. - Where it's used: called by
SetUserAvatarHandleras the first gate on an upload (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarHandler.cs:63) before the bytes reachIImageProcessor(SetUserAvatarHandler.cs:103) and thenIFileStorageService(SetUserAvatarHandler.cs:117). It has its own dedicated unit-test class (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/ImageContentSnifferTests.cs). - Caveats / not-in-source: sniffing establishes only that the prefix matches a known signature. It is
not a decode, so a truncated or malformed body still passes here and is rejected later by
IImageProcessor.
DocumentContentSniffer
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Storage·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/DocumentContentSniffer.cs:49· Level 1 · class (public static)
- What it is: a dependency-free static helper that decides the canonical MIME type of uploaded document bytes by checking both the file name's extension and the content's actual bytes, refusing to trust either one alone.
- Depends on:
DocumentFormats; BCLZipArchive,Utf8.IsValid. It is the document-side counterpart toImageContentSniffer. - Concept introduced, extension-plus-signature agreement as an upload trust boundary.
[Rubric §11, Security]assesses whether untrusted input is validated by its actual content rather than a spoofable extension or client-declared content type; this type requires both the extension and the bytes to agree before it will return a MIME type, whichImageContentSnifferdoes not need because an image has no user-visible extension trust decision to make. A zip-bomb guard (MaxInspectedEntries = 4096,DocumentContentSniffer.cs:61) caps how many zip central-directory entries are inspected, and only entry names are read, never entry streams (DocumentContentSniffer.cs:175-177), so a hostile archive costs nothing to refuse. - Walkthrough: a lookup table plus detection and signature-checking members.
KnownExtensions(DocumentContentSniffer.cs:68-79): the one place extension,DocumentFormatsflag and canonical MIME type are tied together, compared case-insensitively.Detect(ReadOnlySpan<byte> content, string fileName, DocumentFormats allowed)(DocumentContentSniffer.cs:91-106): resolves the extension, then for Office Open XML formats copies the span to an array (ZipArchiveneeds a seekable stream) and callsIsOfficeOpenXml; otherwise checks the format's byte signature directly.Detect(ReadOnlyMemory<byte> content, string fileName, DocumentFormats allowed)(DocumentContentSniffer.cs:119-131): the same contract without the defensive copy, for callers that already hold aMemory<byte>.IsPdf(DocumentContentSniffer.cs:136-137): leading bytes match%PDF-.IsZip(DocumentContentSniffer.cs:142-143): leading bytes match the zip local-file-header signaturePK 03 04.IsOfficeOpenXml(ReadOnlyMemory<byte> content)(DocumentContentSniffer.cs:153-188): opens the bytes as aZipArchiveand checks for a[Content_Types].xmlentry, the marker every Office Open XML package carries at its root; a malformed or truncated archive answersfalserather than throwing (DocumentContentSniffer.cs:179-187).IsPlainUtf8Text(DocumentContentSniffer.cs:197-211): strips an optional UTF-8 BOM, then rejects empty content, any embedded NUL byte, or anythingUtf8.IsValidrejects.TryResolve/MatchesSignature/Extension(DocumentContentSniffer.cs:216-267): the private glue that looks up the extension, checks it againstallowed, and routes to the right signature check.
- Why it's built this way: requiring extension and signature to agree stops both a renamed executable and a correctly-named file with forged content; reading only zip entry names (never opening entry streams) and capping inspected entries at 4096 make the Office Open XML check itself resistant to a zip bomb rather than merely fast.
- Where it's used:
UploadSessionAssetHandlerandUploadSessionAssetCommandValidatorcallDetectto accept or reject an uploaded document (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/UploadFile/UploadSessionAssetCommandValidator.cs:1,UploadSessionAssetHandler.cs:1);SessionAssetValidationRulesandSessionAssetLimitsalso reference it (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/Validation/SessionAssetValidationRules.cs:1,MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/SessionAssets/SessionAssetLimits.cs:1). It has its own dedicated unit-test class (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DocumentContentSnifferTests.cs).
IFileStorageService
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Infrastructure.Storage·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/IFileStorageService.cs:15· Level 3 · interface
- What it is: the contract for storing and deleting binary blobs, for example user avatar images. Implementations own the container or bucket; callers pass only a blob name scoped within it.
- Depends on:
Resultand its generic form (viaMMCA.Common.Shared.Abstractions,IFileStorageService.cs:1);FileUploadOptions; BCLStreamandUri. - Concept introduced, the managed blob-storage boundary.
[Rubric §8, Data Architecture]assesses whether data lands in the right store, and binary content belongs in object storage rather than in a relational row.[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether a transport like this is swappable behind an abstraction. Per the doc comment (IFileStorageService.cs:5-14, ADR-045) the default implementation is unconfigured (uploads fail with a clear error) until a host callsAddAzureBlobFileStorage(configuration)with a completeFileStoragesection. ReturningResultrather than throwing keeps a failed upload on the same error-flow rails as the rest of the stack (see the primer). - Walkthrough: one property and three methods.
IsConfigured(IFileStorageService.cs:18): whether a real store is wired, so a handler can gate a feature on it rather than attempt a doomed upload.UploadAsync(string blobName, Stream content, string contentType, CancellationToken cancellationToken = default)(IFileStorageService.cs:26): uploads or overwrites a blob and returns its public absolute URL asResult<Uri>. The blob name is container-scoped, for exampleavatars/42-a1b2c3d4.jpg(IFileStorageService.cs:21), and the content is read from the stream's current position (IFileStorageService.cs:22).UploadAsync(string blobName, Stream content, string contentType, FileUploadOptions options, CancellationToken cancellationToken = default)(IFileStorageService.cs:41): the overload a document upload wants, storing the response headers carried byFileUploadOptions(aContent-Disposition, for example, is what makes a stored blob come back as a download under its original file name). It has no default body: every implementation must honor the headers directly rather than falling back to the three-argument overload. It carries aSuppressMessagefor analyzerRS0026(multiple public overloads with optional parameters) (IFileStorageService.cs:40): the justification records it as a grandfathered public overload shipped after the v1.152 public-API baseline, so changing its signature would be a breaking change.DeleteAsync(string blobName, CancellationToken cancellationToken = default)(IFileStorageService.cs:47): deletes a blob; unknown names succeed (idempotent,IFileStorageService.cs:43), which matches at-least-once cleanup semantics.
- Why it's built this way: an unconfigured default plus an
IsConfiguredgate means the framework ships avatar support without forcing every consumer to provision blob storage, and idempotent delete makes cleanup safe to retry after a partial failure. The headers-aware overload is a plain interface member with no default implementation (IFileStorageService.cs:41), so everyIFileStorageServiceimplementation is forced to honor the response headers rather than silently dropping them via a forwarding default. - Where it's used:
SetUserAvatarHandleruploads the normalized JPEG (SetUserAvatarHandler.cs:30for the injection,:117for the call). Deletes run throughDeleteBlobInternalCommandHandlerBase<TCommand>, which takes the service (MMCA.Common/Source/Core/MMCA.Common.Application/InternalCommands/DeleteBlobInternalCommandHandlerBase.cs:29) and callsDeleteAsync(DeleteBlobInternalCommandHandlerBase.cs:45):DeleteAvatarBlobInternalCommandHandlerderives from it (DeleteAvatarBlobInternalCommandHandler.cs:20) and is the cleanup side scheduled bySetUserAvatarHandler,RemoveUserAvatarHandlerandDeleteUserHandler.UploadSessionAssetHandleruses the headers-aware overload for document uploads (UploadSessionAssetHandler.cs:164), withDeleteSessionAssetBlobInternalCommandHandleron its cleanup side (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/SessionAssets/UseCases/DeleteSessionAssetBlob/DeleteSessionAssetBlobInternalCommandHandler.cs:20).NullFileStorageServiceis the default registration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:433);AzureBlobFileStorageServicereplaces it when configured (MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:71).
EntityConfigurationOptions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EntityConfigurationOptions.cs:10· Level 0 · class (sealed)
- What it is: an options bag that carries extra assemblies whose EF Core entity type
configurations should be applied on top of the ones auto-discovered by name. A host or module pushes
an
Assemblyinto it during DI so its configurations are picked up without the discovery scan having to match it by naming convention. - Depends on:
System.Reflection.Assembly(BCL); nothing first-party. It is read byDefaultEntityConfigurationAssemblyProviderthroughIOptions<EntityConfigurationOptions>(DefaultEntityConfigurationAssemblyProvider.cs:12-13). - Concept introduced, options-object supplementation of convention discovery.
[Rubric §3, Clean Architecture](assesses whether infrastructure discovers its collaborators rather than hardcoding references to them): the persistence layer does not reference every module's Infrastructure project, so a module that does not follow the.Infrastructurenaming rule (for example a Common feature like Notification that lives insideCommon.Infrastructureitself, which the auto-scan deliberately excludes) still gets its configurations applied by adding its assembly here. The doc comment names exactly that case (EntityConfigurationOptions.cs:5-9). - Walkthrough: one member,
List<Assembly> AdditionalAssemblies { get; } = [](EntityConfigurationOptions.cs:16). It is get-only and initialized to an empty list, so registration code mutates the list rather than replacing it. - Why it's built this way: an options object keeps the supplemental-assembly list open for extension without the provider (or the context) taking a compile-time dependency on any specific module. The provider merges these with the name-scanned set and de-duplicates.
- Where it's used: written through the
AddEntityConfigurationAssembly(Assembly)extension (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:445-455), which callsservices.Configure<EntityConfigurationOptions>with a contains-check so an assembly is added at most once (DependencyInjection.cs:447-453);AddNotificationInfrastructure(IConfiguration)(DependencyInjection.Notifications.cs:29-34) is the one in-framework caller. It is read byDefaultEntityConfigurationAssemblyProvider.
PersistenceSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/PersistenceSettings.cs:10· Level 0 · class (sealed)
- What it is: the bound
Persistenceconfiguration section, with two knobs: the SQL command timeout applied to every command the SQL Server and PostgreSQL contexts issue (PersistenceSettings.cs:16-17), and the request to let EF render parameter values into its logs. - Depends on:
System.ComponentModel.DataAnnotations(for[Range],PersistenceSettings.cs:1); nothing first-party. - Concept introduced, the defaults-preserve-history rule for a new settings section.
[Rubric §15, Best Practices & Code Quality]assesses whether change is additive; the class doc states the policy directly, every property defaults to the value the framework applied implicitly before the section existed, so the section is optional inappsettings.json(PersistenceSettings.cs:5-9).[Rubric §12, Performance & Scalability]: the 30-second default is the previous implicit ADO.NET behavior, and the doc names the case for raising it (reporting-style workloads whose queries legitimately run longer than half a minute,PersistenceSettings.cs:15-20). Making that value configurable rather than constant is the difference between tuning an environment and cutting a release. - Walkthrough:
SectionName = "Persistence"(PersistenceSettings.cs:13);CommandTimeoutSeconds,[Range(1, 600)]-validated (PersistenceSettings.cs:21) and defaulting to30(PersistenceSettings.cs:22), is the timeout property. The consuming side is defensive in a way worth copying:SQLServerDbContextresolves the options withGetService<IOptions<PersistenceSettings>>()?.Value ?? new PersistenceSettings()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/SQLServerDbContext.cs:35-36), so a context built outside the full DI graph (the design-time provider behinddotnet ef, a test) still gets the documented default rather than a null reference. It then applies it withsql.CommandTimeout(_persistenceSettings.CommandTimeoutSeconds)(SQLServerDbContext.cs:55).PostgreSQLDbContextdoes the same: the identical null-coalescing resolve (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/PostgreSQLDbContext.cs:44-45) andnpgsql.CommandTimeout(_persistenceSettings.CommandTimeoutSeconds)(PostgreSQLDbContext.cs:94). A second property,EnableSensitiveDataLogging, defaults tofalse(PersistenceSettings.cs:44) and asks EF to render parameter VALUES into its logs and exception messages (EnableSensitiveDataLogging,PersistenceSettings.cs:25-26);SensitiveDataLoggingGateis the class that decides whether the request is actually honored. - Why it's built this way: a
[Range]-validated option bound withValidateDataAnnotations()andValidateOnStart()turns a typo into a startup failure rather than a per-query surprise (ADR-070).EnableSensitiveDataLoggingis deliberately a request, not a switch: the doc comment is explicit that setting ittruematters only when the host also reports the Development environment, and a host with noIHostEnvironmentregistered (design time, a directly-constructed test context) counts as not Development (PersistenceSettings.cs:29-34), so the flag cannot by itself put parameter values (customer data, tokens, password hashes) into a log sink in Staging or Production (ADR-122). The flag also does not by itself make EF log statements: the doc comment pairs it with settingLogging:LogLevel:Microsoft.EntityFrameworkCore.Database.CommandtoInformationinappsettings.Development.jsononly (PersistenceSettings.cs:37-41). - Where it's used: bound in the infrastructure registration
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:151-154) and read bySQLServerDbContextandPostgreSQLDbContextfor the command timeout; the Sqlite and Cosmos contexts do not read that property.EnableSensitiveDataLoggingis read bySensitiveDataLoggingGate, whichApplicationDbContextcalls fromConfigureSensitiveDataLogging(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:594-602) so the guarantee applies on the shared base rather than per engine.
ProfilingHelper
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/ProfilingHelper.cs:9· Level 0 · class (internal static)
- What it is: an internal static helper that wraps repository operations in a MiniProfiler timing step when profiling is active and is a no-op when it is not.
- Depends on:
StackExchange.Profiling(the MiniProfiler NuGet package); nothing first-party. - Concept introduced, opt-in per-operation timing via a null-conditional.
[Rubric §13, Observability & Operability](assesses granular timing and instrumentation of persistence): every helper routes throughMiniProfiler.Current?.Step(...)(ProfilingHelper.cs:11-12). When MiniProfiler is not registered,MiniProfiler.Currentisnull, the?.short-circuits, and the returnedTiming?isnull, sousing var step = ...disposes nothing. The instrumentation can therefore live permanently in the decorators without a build-time toggle; the runtime cost when disabled is a single field read. - Walkthrough:
BeginStep(className, methodName)(ProfilingHelper.cs:11-12): returns aTiming?namedMMCA.Common.Infrastructure.{className}: {methodName}, so every step in the profiler tree is self-identifying.Profile(className, methodName, Func<int>)(ProfilingHelper.cs:14-18): opens a step and runs a synchronous delegate returningint(the shape of a syncSave).ProfileAsync(...)non-generic andProfileAsync<T>(...)(ProfilingHelper.cs:20-24,26-30): the async equivalents, each awaiting the delegate under the step withConfigureAwait(false).
- Why it's built this way:
internalhides the profiling concern from callers outside Infrastructure; the null-conditional pattern means the same wrapper is safe in hot paths whether or not profiling is on. - Where it's used: the EF repository decorators wrap every call through it, for example
EFRepositoryDecorator<TEntity, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepositoryDecorator.cs:24-52, coveringAddAsyncthroughExecuteUpdateAsync) andEFReadRepositoryDecorator<TEntity, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepositoryDecorator.cs:33-111, coveringGetAllAsyncthroughCountAsync).ApplicationDbContextopens its own MiniProfiler step directly rather than through this helper (ApplicationDbContext.cs:208). Behavior is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/ProfilingHelperTests.cs.
DefaultEntityConfigurationAssemblyProvider
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DefaultEntityConfigurationAssemblyProvider.cs:12· Level 1 · class (sealed)
- What it is: the default implementation of
IEntityConfigurationAssemblyProvider. It returns the set of assemblies whose EF entity configurations should be applied: every loaded assembly whose name contains.Infrastructure(excludingCommon.Infrastructureitself), plus any assemblies explicitly registered throughEntityConfigurationOptions. - Depends on:
IEntityConfigurationAssemblyProvider(the contract it implements),EntityConfigurationOptionsviaIOptions<>(DefaultEntityConfigurationAssemblyProvider.cs:12-13), andSystem.AppDomainplusSystem.Reflection(BCL). - Concept introduced, name-convention assembly discovery with an explicit escape hatch.
[Rubric §3, Clean Architecture](infrastructure finds module configurations without referencing modules) and[Rubric §7, Microservices Readiness](each extracted service loads only its own modules' configuration assemblies): scanningAppDomain.CurrentDomain.GetAssemblies()means a host applies exactly the module infrastructure it has loaded, so a monolith gets all modules and an extracted service gets its subset, with no per-host registration list. - Walkthrough:
GetConfigurationAssemblies()(DefaultEntityConfigurationAssemblyProvider.cs:16) builds a collection expression from two spreads: the loaded assemblies whoseFullNameis non-null, contains.Infrastructure, and does not containCommon.Infrastructure(both matchedOrdinalIgnoreCase,DefaultEntityConfigurationAssemblyProvider.cs:17-20), and the distinctoptions.Value.AdditionalAssemblies(DefaultEntityConfigurationAssemblyProvider.cs:21). TheCommon.Infrastructureexclusion is why Common-internal feature modules must opt in throughEntityConfigurationOptions. - Why it's built this way:
sealed; convention scanning keeps hosts declarative, and the additional-assemblies list covers the one case the convention deliberately excludes. Depending only on the abstraction plus options keeps the persistence layer free of module references. - Where it's used: registered as the singleton
IEntityConfigurationAssemblyProviderviaTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:61) and resolved byApplicationDbContext, which iterates its assemblies insideApplyConfigurationsForEntitiesInContext(ApplicationDbContext.cs:1073,1092). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/DefaultEntityConfigurationAssemblyProviderTests.cs.
EfCoreConcurrencyConflictDetector
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EfCoreConcurrencyConflictDetector.cs:18· Level 1 · class (sealed)
- What it is: the shipped implementation of
IConcurrencyConflictDetector. Given the exception a failed save threw, it answers whether the failure was an optimistic-concurrency conflict (a row-version mismatch), the same roleSqlServerUniqueConstraintViolationDetectorplays for unique-constraint violations, but for a condition EF itself already classifies rather than one that has to be inferred from a provider error number. - Depends on:
IConcurrencyConflictDetector(the Application-layer contract it implements) andMicrosoft.EntityFrameworkCore.DbUpdateConcurrencyException. - Concept introduced, classifying a framework exception without leaking it past Application.
[Rubric §3, Clean Architecture](provider and framework vocabulary stays out of Application) and[Rubric §29, Resilience & Business Continuity](a lost optimistic-concurrency race becomes a deterministic conflict answer rather than an unhandled exception):DbUpdateConcurrencyExceptionis an EF Core type, so a handler cannot catch it directly without referencing EF; this detector is the one place that does, behind the same abstraction the unique-constraint detector uses. - Walkthrough: one method,
IsConcurrencyConflict(Exception exception)(EfCoreConcurrencyConflictDetector.cs:20-31). Aforloop walks the exception chain (current = exception, thencurrent.InnerException) and returnstrueon the first link that is aDbUpdateConcurrencyException(:22-28),falseonce the chain is exhausted (:30). UnlikeSqlServerUniqueConstraintViolationDetectorthere is no provider-number or message fallback: EF raisesDbUpdateConcurrencyExceptiondirectly when aSaveChangescall affects zero rows for a concurrency-token-checked entity, so no wrapping or translation step needs covering. - Why it's built this way:
sealedand stateless, so it can be registered as a singleton. The chain walk exists becauseSaveChangesAsynccan be called from inside a transaction helper that wraps the original exception; checking only the outermost exception would miss that case. - Where it's used: registered as the singleton
IConcurrencyConflictDetectorviaTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:128). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/EfCoreConcurrencyConflictDetectorTests.cs.
EFQueryableExecutor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EFQueryableExecutor.cs:11· Level 1 · class (internal sealed)
- What it is: the EF Core bridge for the Application layer's
IQueryableExecutor. It exposesInclude,AsSplitQuery,ToListAsync, andCountAsyncover anIQueryable<T>, guarding each so the same code path works against a real EF queryable and against a plain in-memoryIQueryable. - Depends on:
IQueryableExecutor(the Application-layer contract it implements),SpecificationEvaluator(its internalApplyIncludescarries the include path and the split-query heuristic) andMicrosoft.EntityFrameworkCore(EntityFrameworkQueryableExtensions). - Concept introduced, provider-agnostic query execution.
[Rubric §14, Testability](assesses whether query logic can run without a database) and[Rubric §3, Clean Architecture](keeps EF's async extension methods behind an Application abstraction): the Application layer builds specifications and callsIQueryableExecutorrather than EF directly, so the same handlers execute against a LINQ-to-Objects list in a unit test and against a SQL provider in production. - Walkthrough:
Include<T>(EFQueryableExecutor.cs:19-23): on an EF queryable, hands the single path toSpecificationEvaluator.ApplyIncludes(query, [navigationPropertyPath])(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/SpecificationEvaluator.cs:87), which applies EF's string-basedIncludeand switches the query to split mode when the path targets a collection navigation (SpecificationEvaluator.cs:95-103). That method is the single home of the split-query heuristic, so the per-navigation calls fromEntityQueryPipelinebehave exactly like the specification and repository string-include paths (SpecificationEvaluator.cs:77-82). On an in-memory queryable the query is returned unchanged (it is already fully loaded).AsSplitQuery<T>(EFQueryableExecutor.cs:26-30): applies EF's split-query behavior only on EF queryables, otherwise a pass-through.ToListAsync<T>(EFQueryableExecutor.cs:33-36): uses EF's async materialization when available, otherwise the synchronous collection expression[.. query].CountAsync<T>(EFQueryableExecutor.cs:39-42): EF async count when available, otherwiseTask.FromResult(query.Count()).IsEfQuery<T>(EFQueryableExecutor.cs:48): the discriminator. An EF provider's queryable implementsIAsyncEnumerable<T>, a plain LINQ-to-Objects queryable does not, so a singleis IAsyncEnumerable<T>test routes every call above.
- Why it's built this way:
internal sealed; centralizing the EF versus in-memory branch in one class means every consumer gets the fallback for free and no handler references EF's static extension methods. - Where it's used: registered as the singleton
IQueryableExecutor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:113) and injected into Application-layer query code:EntityQueryPipeline(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:14), the Common notification handlers (GetMyNotificationsHandler.cs:18,GetUnreadNotificationCountHandler.cs:15,GetNotificationHistoryHandler.cs:17,MarkNotificationReadHandler.cs:14,MarkAllNotificationsReadHandler.cs:14) and app code such asMMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/SessionQuestions/Services/SessionQuestionViewBuilder.cs:12. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/EFQueryableExecutorTests.csand, for the collection-include split behavior,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/SplitQueryHeuristicTests.cs.
NamespaceConventions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/NamespaceConventions.cs:11· Level 1 · class (internal static)
- What it is: the persistence layer's one-method entry point for deriving a module name from an
entity type's namespace. It is a thin forwarder: the parsing itself lives in
ModuleNameConventionsinMMCA.Common.Shared, so SQL schema names, logical database names and the module label the CQRS logging decorators enrich their scopes with all come from one rule. - Depends on:
ModuleNameConventions(NamespaceConventions.cs:1,20-21); nothing else. - Concept introduced, convention-over-configuration naming with a single shared parser.
[Rubric §8, Data Architecture](assesses schema and database organization),[Rubric §7, Microservices Readiness](assesses whether the model splits cleanly per module) and[Rubric §15, Best Practices & Code Quality](one rule, one implementation):MMCA.Store.Sales.Domain.Ordersyields"Sales", which becomes both the[Sales]SQL schema and theSaleslogical database name (the worked examples are in the doc comment,NamespaceConventions.cs:14-16). A new module that follows the namespace pattern gets a schema and a data-source name with zero configuration; an explicit[UseDatabase("X")]attribute on a configuration overrides it when the pattern does not fit. The parse was lifted into Shared because Application may not reference Infrastructure and the logging decorators need the same answer (NamespaceConventions.cs:6-9). - Walkthrough:
GetModuleName(Type entityType)(NamespaceConventions.cs:20-21) delegates straight toModuleNameConventions.GetModuleName(MMCA.Common/Source/Core/MMCA.Common.Shared/Conventions/ModuleNameConventions.cs:38-51). That method splits the namespace on., defaulting to an empty array whenNamespaceis null (ModuleNameConventions.cs:40), and applies two rules in order:- The
Domainrule (ModuleNameConventions.cs:41-46): the case-insensitive index of aDomainsegment, and when that index is>= 1the preceding segment wins. This is the original persistence rule, kept byte for byte so schema and data-source naming never move. - The other layer segments (
ModuleNameConventions.cs:17,48-50):Application,Infrastructure,APIandUImatch only at the fourth segment or later (layerIndex >= 3), so a framework namespace such asMMCA.Common.Application.*resolves tonullrather than to a phantom"Common"module.Sharedis deliberately absent from that list.
- The
- Why it's built this way: a single authority for both derivations means the schema name and the
database name are computed identically, so they cannot diverge; keeping the parser in Shared lets
Application reuse it without a layer violation.
NamespaceConventionsstaysinternalbecause callers inside Infrastructure should consume the resolved name, not re-derive it. - Where it's used:
EntityDataSourceRegistryfalls back to it when no[UseDatabase]is present and then toDataSourceKey.DefaultName(EntityDataSourceRegistry.cs:168), andEntityTypeConfiguration<TEntity, TIdentifierType>hands mapping to the engine (EntityTypeConfiguration.cs:78), which uses it for the SQL table schema (SQLServerDataSourceEngine.cs:101,PostgreSQLDataSourceEngine.cs:100, falling back todbo) and the Cosmos container name (CosmosDataSourceEngine.cs:110, falling back to the entity type name). The Shared parser is separately exercised byMMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Conventions/ModuleNameConventionsTests.cs, and the persistence forwarder byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/EntityDataSourceRegistryTests.cs:54,58.
SensitiveDataLoggingGate
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SensitiveDataLoggingGate.cs:24· Level 1 · class (static)
- What it is: the one-method static class that answers whether EF Core is allowed to render
parameter VALUES into its logs and exception messages. It is the enforcement point for the
and-gate
PersistenceSettings.EnableSensitiveDataLoggingdocuments: the setting alone is a request, this gate is what turns it into an actualtrue. - Depends on:
PersistenceSettings(the setting it reads) andMicrosoft.Extensions.Hosting.IHostEnvironment(IsDevelopment()). - Concept introduced, fail-closed AND-gating of a dev-only relaxation.
[Rubric §17, Security & Compliance]and[Rubric §29, Resilience & Business Continuity]: a configuration value that leaks into a Staging or Production file, container image, or environment variable must not by itself enable logging of parameter values (customer data, tokens, password hashes). Requiring both the setting ANDIHostEnvironment.IsDevelopment()means either absence, including a host that registers noIHostEnvironmentat all (design time, a directly-constructed test context), reads as "off" (ADR-122). - Walkthrough:
IsEnabled(PersistenceSettings? settings, IHostEnvironment? environment)(SensitiveDataLoggingGate.cs:33-34) is one expression:settings?.EnableSensitiveDataLogging == true && environment?.IsDevelopment() == true. Both parameters are nullable and both null-conditional comparisons resolve tofalserather than throwing, so a caller that could not resolve either dependency from DI still gets a safe answer instead of aNullReferenceException. - Why it's built this way:
staticbecause the method is a pure function of its two inputs with no state to hold; comparing with== truerather than?? falsekeeps the short-circuit reading left to right as "did the host ask, AND is it Development". - Where it's used: called from
ApplicationDbContext'sConfigureSensitiveDataLogging(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:596-598), which callsoptionsBuilder.EnableSensitiveDataLogging()only when the gate returnstrue(ApplicationDbContext.cs:600); the method sits on the shared base rather than in each engine's context class so the guarantee holds identically for every engine. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/SensitiveDataLoggingGateTests.cs.
SqlServerUniqueConstraintViolationDetector
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SqlServerUniqueConstraintViolationDetector.cs:37· Level 1 · class (sealed)
- What it is: the shipped implementation of
IUniqueConstraintViolationDetector. Given the exception a failed save threw, it answers whether the database rejected the write for violating a unique constraint, so a handler whose pre-check lost a race against a concurrent insert can return the same conflict result the pre-check would have produced. - Depends on:
IUniqueConstraintViolationDetector(the Application-layer contract it implements) and three provider exception types:SqlExceptionfromMicrosoft.Data.SqlClient,SqliteExceptionfromMicrosoft.Data.Sqlite, and the provider-neutralDbExceptionfromSystem.Data.Common(SqlServerUniqueConstraintViolationDetector.cs:1-3). Nothing else: it holds no state and takes no constructor dependencies. - Concept introduced, classifying a provider error without leaking the provider.
[Rubric §3, Clean Architecture](assesses whether provider vocabulary stays in Infrastructure): the Application layer referencesMMCA.Common.Domainand no data provider at all, so neitherSqlExceptionnor the EF CoreDbUpdateExceptionwrapping it is reachable from a handler (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IUniqueConstraintViolationDetector.cs:9-25). Asking a handler to match on the exception message is what that constraint used to force, and that is wrong twice over: the wording is a provider and locale detail, and matching on it drags provider vocabulary into the layer whose purpose is to stay persistence neutral.[Rubric §29, Resilience & Business Continuity]also applies: the pattern turns a lost insert race into a deterministic conflict answer rather than an unhandled 500, and a miss is safe rather than silent, because an unclassified exception simply keeps propagating. - Walkthrough: one public method,
IsUniqueConstraintViolation(Exception exception)(SqlServerUniqueConstraintViolationDetector.cs:61-86), and one private helper,IsUniqueViolationByCode(Exception exception)(:93-99).Chain walk (
:63): aforloop overcurrent = exceptionthencurrent.InnerException. EF surfaces a rejected insert as aDbUpdateExceptionwrapping the provider exception, so testing only the outermost exception would never match (:13-14).Code check (
:65-68, the helper at:93-99): each link is first asked for the provider's own code, never its wording, through a typeswitchwhose first matching arm decides:- a
SqlExceptionclassifies when itsNumberis 2601 (duplicate key rejected by a unique INDEX,:40) or 2627 (duplicate key violating a PRIMARY KEY or UNIQUE constraint,:43) (:95); - a
SqliteExceptionclassifies when itsSqliteExtendedErrorCodeis 2067 (SQLITE_CONSTRAINT_UNIQUE,:49) or 1555 (SQLITE_CONSTRAINT_PRIMARYKEY,:52) (:96); - any other
DbExceptionclassifies when itsSqlStateis23505(:46, PostgreSQL's unique_violation), comparedOrdinal(:97). That is how Npgsql'sPostgresExceptionis recognised without the detector naming an Npgsql type, and the class doc notes the SQLSTATE is reported whatever the server'slc_messageslocale (:23-27); - anything else is
false(:98).
Because the arms are tried in order, a
SqlExceptionorSqliteException(both of which areDbExceptions) is judged by its own code only and never falls through to the SQLSTATE arm. Every other SQL Server error (a foreign-key failure, a deadlock victim, a timeout) is deliberately not a unique violation by number and must keep propagating, because treating it as a collision would either loop or hide a real fault (:16-19).- a
Message fallback (
:70-82): a link the code check did not classify still classifies when its message containsduplicate key(:55, the wording SQL Server and an English-locale PostgreSQL share) orUNIQUE constraint failed(:58, SQLite), both matchedOrdinalIgnoreCase(:78-79). It runs on every link, a provider exception whose code did not match included, which the class doc and the inline comment both state (:19-20,:70-72). The comment is explicit that this is a fallback only, for a wrapper that captured the provider failure as text (a retry decorator re-throwing its own type, another engine's provider, a test double), and that the error numbers themselves are never matched as text: they do not appear in the message, so searching for them would match nothing real while happily matching an unrelated exception that quoted those digits (:72-77). The class doc places the fallback after the other engines' codes, for a link that carries no code (:28-30).Default (
:85):falseonce the chain is exhausted.
- Why it's built this way:
sealedand stateless by construction (:33-34), which is what lets the container register it as a singleton. Despite the name it is also the default registration for hosts running another engine (:23), which is why the PostgreSQL and SQLite codes are checked before any text: a host on a non-English PostgreSQL locale still gets a deterministic answer from SQLSTATE23505rather than depending on the English wording. Matching PostgreSQL throughDbException.SqlStaterather than a provider type keeps that arm provider neutral. Because the registration is aTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:123), a host that registers its own detector first keeps it. - Where it's used: registered as the singleton
IUniqueConstraintViolationDetectorviaTryAddSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:123), which the module registrations rely on rather than shipping their own pair (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Infrastructure/DependencyInjection.cs:28-31).DbSeederalso constructs it directly as the fallback when the unit of work is not itself a detector (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Seeding/DbSeeder.cs:98). Inside the framework,EFPermissionGrantStoretakes the contract as a constructor dependency (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFPermissionGrantStore.cs:41), and its tests pass this class in directly (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Auth/EFPermissionGrantStoreTests.cs:65). The consumers are the handlers whose uniqueness pre-check can lose a race:MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/Create/CreateSessionHandler.cs:30,.../Questions/UseCases/Create/CreateQuestionHandler.cs:25,MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/UserSessionBookmarks/UseCases/Create/CreateBookmarkHandler.cs:22,.../CheckIns/UseCases/GetOrCreateMyBadge/GetOrCreateMyBadgeHandler.cs:22,.../LivePolls/UseCases/CastVote/CastVoteHandler.cs:26,.../SessionQuestions/UseCases/ToggleUpvote/ToggleUpvoteHandler.cs:23,.../Points/Services/PointsAwarder.cs:39and.../Points/UseCases/SetLeaderboardParticipation/SetLeaderboardParticipationHandler.cs:36. Behavior is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/SqlServerUniqueConstraintViolationDetectorTests.cs, including a PostgreSQL23505with a localized message (:112), another SQLSTATE that must not classify (:124), a real SQLite constraint failure asserting the 2067 or 1555 extended code (:136-145), and a SQLite NOT NULL failure that must not classify (:158); the registration is pinned byDependencyInjectionInfrastructureTests.cs:150-157. - Caveats / not-in-source: because the message fallback runs on every link, any exception whose
message happens to contain
duplicate keyclassifies as a collision. That is the deliberate trade the comment describes; whether a real provider emits that wording for a non-unique failure is Not determinable from source. The opening line of the inline comment still frames the fallback as being for "a link in the chain that is not a SqlException" (:70-71), which predates the SQLite and SQLSTATE arms; the code itself runs the fallback after all three.
SoftDeleteFilterSql
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SoftDeleteFilterSql.cs:18· Level 11 · class (internal static)
- What it is: the internal static class that owns the soft-delete index predicate for unique and
opted-in indexes. It resolves which column carries the flag, hands that column to the target engine
to spell the predicate, recognises when an index filter already carries that predicate, and quotes
a single column name the way the engine expects. It is the single authority both the automatic
convention and the hand-authored opt-in call, so the two can never disagree
(
SoftDeleteFilterSql.cs:9-17). - Depends on:
DataSource(the engine enum),DataSourceEnginesandIDataSourceEngine(the per-engine strategy that owns the quoting and the predicate spelling),IAuditableEntity(for thenameof(IAuditableEntity.IsDeleted)property name), and EF Core'sMicrosoft.EntityFrameworkCore.Metadata.IReadOnlyEntityTypeplus theGetColumnName()relational metadata extension. - Concept introduced, one predicate entry point shared by a convention and an explicit extension.
[Rubric §8, Data Architecture](assesses whether soft-delete is honored by the schema, not just by query filters) and[Rubric §15, Best Practices & Code Quality](assesses whether one rule has one implementation): a filtered unique index that hardcodes the literal"[IsDeleted] = 0"breaks in two ways, on a model that renames the column withHasColumnNameand on a provider that quotes identifiers with double quotes rather than brackets. Reading the column name from the EF model and asking the engine strategy for the spelling fixes both, and putting that entry point in one place means the automatic path (SoftDeleteUniqueIndexConvention) and the opt-in path (IndexBuilderExtensions) emit byte-identical SQL. The engine-specific text itself no longer lives in this class: it is one member per engine onIDataSourceEngine, so this class carries noswitchoverDataSource. - Walkthrough:
Build(DataSource engine, IReadOnlyEntityType entityType)(SoftDeleteFilterSql.cs:35-36) is one expression:DataSourceEngines.For(engine).BuildSoftDeleteFilter(ColumnName(entityType)). The privateColumnNamehelper (:72-74) looks theIsDeletedproperty up in the entity type and takes its mapped column name, falling back to the CLR property name when the property is not in the model, so aHasColumnNamerename follows automatically. The engine then answers the spelling: SQL Server[Column] = 0(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:117), PostgreSQL"Column" = false(PostgreSQLDataSourceEngine.cs:116), because it maps the flag to a real boolean column and refuses to compare one with an integer, the only place the predicate differs by engine beyond quoting (SoftDeleteFilterSql.cs:29-34), Sqlite"Column" = 0(SqliteDataSourceEngine.cs:115), and Cosmosnull(CosmosDataSourceEngine.cs:129), since it has no filtered-index support.nullis the contract for "leave the index untouched", and both callers check it before doing anything (SoftDeleteUniqueIndexConvention.cs:58-59,IndexBuilderExtensions.cs:59-60).ContainsPredicate(string existingFilter, IReadOnlyEntityType entityType)(SoftDeleteFilterSql.cs:53-60) answers the idempotence question: does a filter already declared on an index constrain the soft-delete column? Both the integer spelling ({column} = 0) and the PostgreSQL boolean spelling ({column} = false) are checked, each pushed throughNormalize(:77-78), which strips whitespace and the three identifier quoting styles ([,],"and a backtick), so a hand-authored[IsDeleted] = 0, a"IsDeleted"=0, the PostgreSQL"IsDeleted" = falseand the predicateBuildproduces all count as the same clause. Without that normalization, and without checking both spellings, the convention could append its own predicate to a filter that already had one, or append the integer and boolean spellings of the same predicate to one another.QuoteColumn(DataSource engine, string column)(SoftDeleteFilterSql.cs:70-71) forwards toDataSourceEngines.For(engine).QuoteColumn(column): brackets on SQL Server, the SQL-standard double-quoted form on PostgreSQL (which rejects brackets) and SQLite (:61-68). It exists for filtered-index predicates over columns other thanIsDeleted, such as anIS NOT NULLclause.
- Why it's built this way:
internal staticwith a nullableBuildreturn keeps the engine-capability decision out of the call sites; delegating the spelling to the engine strategy keeps the per-engine text in one place per engine rather than in aswitchhere. The Cosmosnullis a deliberate signal instead of an exception, because both callers run over whole models where Cosmos entities are simply skipped. Comparing on a normalized form rather than on the exact string is what lets the two entry points, which do not agree on quoting, still recognise each other's output. - Where it's used:
SoftDeleteUniqueIndexConventioncallsBuildat model finalization andContainsPredicatebefore combining (SoftDeleteUniqueIndexConvention.cs:57,75), andIndexBuilderExtensionscallsBuildfor a hand-authored index (IndexBuilderExtensions.cs:58).QuoteColumnis called byPushNotificationConfigurationfor itsDedupKey IS NOT NULLfilter (PushNotificationConfiguration.cs:83) and byApplicationDbContextthrough a private wrapper (ApplicationDbContext.cs:861-862) for the outbox and internal-command partial-index predicates (ApplicationDbContext.cs:905-906,1024-1025). - Caveats / not-in-source: a fifth engine would need its own
IDataSourceEngineimplementation to answerBuildSoftDeleteFilterandQuoteColumn; howDataSourceEngines.For(DataSourceEngines.cs:40) treats an unmapped value is not covered by this section.
EFRawSqlQueryExecutor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EFRawSqlQueryExecutor.cs:29· Level 13 · class (internal sealed)
- What it is: the EF Core implementation of
IRawSqlQueryExecutor, the Application-layer escape hatch for a query that is easier to express as literal SQL than as a specification. It builds a parameterizedIQueryable<T>from an interpolatedFormattableStringover the host's default physical data source, then either lists or single-or-defaults it (EFRawSqlQueryExecutor.cs:8-26). - Depends on:
IRawSqlQueryExecutor(the Application-layer contract it implements),IDbContextFactory,IDataSourceResolver, andMicrosoft.EntityFrameworkCore(Database.SqlQuery<T>,EntityFrameworkQueryableExtensions). - Concept introduced, an escape hatch that is absent, not refused, on the wrong engine.
[Rubric §3, Clean Architecture](the raw-SQL surface is still an abstraction, not a directDbContextreference from Application) and[Rubric §8, Data Architecture](a relational-only capability is never silently mis-executed on Cosmos): the class itself carries no engine check. The engine gate lives at registration:AddRawSqlQueryExecutorresolves the framework default engine and registers the executor only whenDataSourceEngines.For(defaultEngine).Capabilities.IsRelational(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:498-511). A Cosmos-default host therefore has noIRawSqlQueryExecutorat all, so a service that injects it fails when the container validates rather than on its first statement (EFRawSqlQueryExecutor.cs:19-25). - Walkthrough: a primary constructor takes
IDbContextFactoryandIDataSourceResolver(EFRawSqlQueryExecutor.cs:29-31).QueryAsync<T>(FormattableString sql, CancellationToken)(:33-34) andQuerySingleOrDefaultAsync<T>(...)(:37-39) both call the privateSqlQueryable<T>(sql)and materialize it withToListAsync/SingleOrDefaultAsync;QueryAsyncis anasyncmethod that awaits withConfigureAwait(false)(:34-35), whileQuerySingleOrDefaultAsyncis a non-async expression body that returns EF'sSingleOrDefaultAsynctask directly (:38-39).SqlQueryable<T>(:46-52) null-guardssql(:48), resolves the default source withdataSourceResolver.ResolveLogical(DataSource.SQLServer, DataSourceKey.DefaultName)(:50), the same way the framework's own tables resolve theirs, letting the resolver substitute the engine a single-engine host actually configured (:13-15), and returnsdbContextFactory.GetDbContext(dataSourceKey).Database.SqlQuery<T>(sql)(:51), EF's own parameterized raw-SQL queryable, composable with further LINQ before materialization. Because the context comes from the scoped factory, the statement shares the caller's connection and any transaction anITransactionalcommand opened (:16-17). - Why it's built this way:
internal sealed, with no engine branching in the body, so the relational-only constraint is decided once, at composition, from the engine's declared capabilities rather than re-checked on every call. TheFormattableStringparameter is the parameterization guarantee: interpolated values become SQL parameters through EF's own handling, not string-concatenated SQL (ADR-125). - Where it's used: registered as the scoped
IRawSqlQueryExecutorviaTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:509), the helper being invoked from the infrastructure registration atDependencyInjection.cs:118. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/EFRawSqlQueryExecutorTests.cs, and named byMMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/DataSourceBranchingFitnessTests.cs.
UnitOfWork
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:20· Level 13 · class (internal sealed)
- What it is: the concrete implementation of
IUnitOfWork, the scoped coordinator every handler injects to obtain repositories and to save. It caches repositories per entity type so all operations in a scope share one change tracker and context. - Depends on:
IDbContextFactory(implemented byDbContextFactory),IDataSourceService,IRepositoryFactory,AuditableAggregateRootEntity<TIdentifierType>, andAuditableBaseEntity<TIdentifierType>. - Concept introduced, the Unit of Work over a database-per-service topology.
[Rubric §2, Design Patterns](Unit of Work plus Repository) and[Rubric §8, Data Architecture](transactions and change-tracker scoping): a handler never knows which database an entity lives in.GetRepositoryresolves the entity's physical source, obtains the matching context, and builds a repository bound to it; caching that repository per scope guarantees one change tracker per database, which is what makes "load aggregate, mutate, one save" correct. - Walkthrough:
- Primary constructor (
UnitOfWork.cs:20-24): takes the context factory, the data-source service, the repository factory, and an optionalIUniqueConstraintViolationDetector(defaultnull), null-guarding the context factory and the repository factory into readonly fields (UnitOfWork.cs:26-27; the data-source service and the detector are used directly from the primary-constructor parameters). IsUniqueConstraintViolation(UnitOfWork.cs:39-40): the type also implementsIUniqueConstraintViolationDetectorand forwards to the host's registered detector, returningfalsewhen none is registered. This lets a framework handler base that only holds the unit of work recognise a save that lost an insert race without taking a new constructor dependency (which would break every subclass); with no detector the exception propagates unchanged._repositories(UnitOfWork.cs:34): aDictionary<Type, object>keyed by the closed generic repository interface (for exampleIRepository<Order, int>), so a repository is created at most once per entity type per scope.GetRepository<TEntity, TIdentifierType>()(UnitOfWork.cs:48-61): on a cache miss, resolves the entity'sDataSourceKeyviadataSourceService.GetDataSourceKey(typeof(TEntity))(UnitOfWork.cs:55), asks the context factory for the matching context (:56), and builds a read-writeIRepository<TEntity, TIdentifierType>throughIRepositoryFactory(:57); constrained toAuditableAggregateRootEntity<TIdentifierType>so only aggregate roots get a mutable repository.GetReadRepository<TEntity, TIdentifierType>()(UnitOfWork.cs:68-81): the same resolution but callsCreateReadOnly(:77) and accepts anyAuditableBaseEntity<TIdentifierType>, returningIReadRepository<TEntity, TIdentifierType>for query handlers.- Save and transaction methods (
UnitOfWork.cs:84-94):SaveChangesAsync(:84-85),RequestExplicitKeyInsert(:88), andExecuteInTransactionAsync(:91-94) all delegate straight to the context factory, because in a multi-database scope the factory is what coordinates saving and transacting across every context the scope touched.RequestExplicitKeyInsertforwards toIDbContextFactory.RequestExplicitKeyInsert(), the engine-neutral signal that the next save may carry explicit values for store-generated keys: each context's engine decides whether those inserts need a per-table toggle (itsIExplicitKeyInsertDialect), an engine with none saves unchanged, and the flag clears after the save (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/IDbContextFactory.cs:34-40). There is no synchronousSaveand no manual begin/commit/rollback on this type. - Disposal (
UnitOfWork.cs:96-122): implements bothDispose(:96-100) andDisposeAsync(:102-110) over avolatile bool _disposedflag (UnitOfWork.cs:36), disposing the context factory exactly once and suppressing finalization on both paths.
- Primary constructor (
- Why it's built this way: the unit of work plus the factory hide the physical topology from
handlers (ADR-006), and
per-scope repository caching guarantees a single change tracker per database. It is
internal sealedbecause consumers only ever see theIUnitOfWorkabstraction (dependency inversion). - Where it's used: registered as the scoped
IUnitOfWorkviaTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:132) and injected into virtually every command and query handler in Common and in both apps, and into the module seeders.
AuditTrailEntry
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailEntry.cs:25· Level 0 · class (sealed)
- What it is: one recorded change to an entity that opted into change history, written in the same
transaction as the change it describes. It is the row shape of the
AuditTrailEntriestable: what changed, on which entity, from what to what, by whom, when, under which trace and which tenant. - Depends on: the
UserIdentifierTypealias forChangedBy(AuditTrailEntry.cs:85, the solution-wide identifier alias described in the primer) and nothing else first-party. It is written byAuditTrailSaveChangesInterceptor, purged byAuditTrailCleanupJob, and projected byAuditTrailReader. - Concept introduced, framework bookkeeping rows versus domain state.
[Rubric §8, Data Architecture](assesses whether persistence mechanics are deliberate: keys, soft-delete, concurrency, retention) and[Rubric §30, Compliance, Privacy & Data Governance](assesses whether history and personal data are governed rather than accumulated). The class comment states the category decision outright (AuditTrailEntry.cs:9-13): this is deliberately not anIAuditableEntity, exactly likeOutboxMessageandScheduledJobEntry. It carries no soft-delete flag (so no global query filter reaches it), no audit stamps of its own (stamping a stamp record is circular), and no concurrency token. Rows are append-only: nothing in the framework updates one, and the only deletion is the retention sweep. - Walkthrough: every member is
init-only except one.Id(AuditTrailEntry.cs:28): aGuiddefaulted toGuid.NewGuid(), so a row is addressable the moment it is constructed, before the database sees it. That matters for the key fix-up below, which needs to find the row by id after the save.EntityType(AuditTrailEntry.cs:35):required, the full CLR type name as a string, not a foreign key. The comment gives the two reasons: the trail outlives the row it describes (a deleted entity keeps its history) and one table spans every audited type.EntityKey(AuditTrailEntry.cs:48):required, the invariant string form of the primary key, with a composite key joined by|in the model's key order. This is the one settable property on the class, and the comment atAuditTrailEntry.cs:42-47records why: an entity with a store-generated key has no key yet when the change is captured, so the interceptor rewrites this single column once the insert has assigned one.PropertyName,OldValue,NewValue(AuditTrailEntry.cs:54,63,72): all nullable. A property carryingPiiAttributeorSensitiveAttribute, anIAuthUsercredential, or a property stored through anEncryptedStringConverter, stores the redaction placeholder on both sides instead of its value (AuditTrailEntry.cs:56-61,65-70; the rules live inAuditTrailSaveChangesInterceptor).Operation(AuditTrailEntry.cs:79):required, one ofAdded,Modified,Deleted. The comment names the consequence that surprises people: a soft delete arrives asModifiedonIsDeleted, which is exactly what it is at the database level.ChangedBy,ChangedOn,CorrelationId,TenantId(AuditTrailEntry.cs:85,88,96,104): the provenance block.ChangedByis null for a save that carried no identity (a background service, a seeder),CorrelationIdis the ambient trace id, andTenantIdcomes fromApplicationDbContext.CurrentTenantIdat capture (ApplicationDbContext.cs:150).- Row shape (
AuditTrailEntry.cs:17-23): aModifiedsave produces one row per property that actually changed, so a trail reads as a field-level history; anAddedorDeletedsave produces a single summary row with a nullPropertyName, because the interesting fact there is the lifecycle event and one row per column at insert time would multiply the table for no extra information.
- Why it's built this way: ADR-075 chose a same-transaction, field-level trail over a post-commit log or a database trigger, and this entity is the shape that follows from it. Redacting personal data at capture rather than at read keeps the trail from becoming a second copy of a data subject's data that erasure would have to chase (ADR-005).
- Where it's used: mapped by
AuditTrailModelContributor.Configure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailModelContributor.cs:26-48) todbo.AuditTrailEntries(AuditTrailModelContributor.cs:29) withEntityTypeat 256 non-unicode characters,EntityKeyat 128,PropertyNameat 128 non-unicode,Operationat 16 non-unicode and bothCorrelationIdandTenantIdat 64 non-unicode (AuditTrailModelContributor.cs:31-36), plus two indexes:IX_AuditTrailEntries_Entityover(EntityType, EntityKey, ChangedOn)for the read path andIX_AuditTrailEntries_ChangedOnfor the retention sweep (AuditTrailModelContributor.cs:40-47). The mapping only happens whenAuditTrail:Enabledis true: the contributor'sAppliesToreturns that flag (AuditTrailModelContributor.cs:23), andApplicationDbContext.OnConfiguringkeeps only the contributors that apply to its source (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:550-554), so a host that never opted in builds exactly the base model (ApplicationDbContext.cs:75-80).
CaptureContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:874· Level 0 · record struct (private readonly, nested)
- What it is: a four-field value carrying the provenance every trail row of one save shares: the acting user, the capture instant, the trace id, and the tenant.
- Depends on: the
UserIdentifierTypealias andSystem.DateTime; nothing else. It is nested insideAuditTrailSaveChangesInterceptorand private to it. - Concept introduced, resolve-once-per-save provenance.
[Rubric §12, Performance & Scalability](assesses whether per-item work is hoisted out of loops on a hot path): a save can produce dozens of trail rows, and every one of them wants the same four values. ReadingActivity.Current, callingTimeProvider.GetUtcNow()and truncating strings once per save rather than once per row is the whole point, and it also guarantees that every row of one save carries an identicalChangedOn, which is what lets a reader group a save back together. - Walkthrough: the positional members are
ChangedBy(nullable user id),ChangedOn(UTC instant),CorrelationId(nullable trace id) andTenantId(nullable), declared atAuditTrailSaveChangesInterceptor.cs:874-878. It is constructed exactly once per capture, inCaptureChanges(AuditTrailSaveChangesInterceptor.cs:230-234), where the trace id and tenant are already truncated to their column widths throughColumnWidth.Truncate(MaxCorrelationIdLength64 andMaxTenantIdLength64,AuditTrailSaveChangesInterceptor.cs:101,104). It is then passed by value intoCaptureEntryandCaptureModifiedProperties, which copy its fields straight onto each newAuditTrailEntry(AuditTrailSaveChangesInterceptor.cs:309-312,367-370). - Why it's built this way:
readonly record structmeans no allocation and no defensive copying concerns for a value that exists only for the duration of oneSavingChangescall;privatekeeps it invisible outside the interceptor. Positional syntax gives it structural equality and a usefulToStringfor free, neither of which the interceptor needs but neither of which costs anything. - Where it's used: only inside
AuditTrailSaveChangesInterceptor.
AuditTrailSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSettings.cs:16· Level 1 · class (sealed)
What it is: the
AuditTrailconfiguration section: whether entity change history is recorded at all, how long a row is kept, and which engine'sDefaultdatabase the read surface queries. Every property has a default, so a host that opts in only needsAuditTrail:Enabled(AuditTrailSettings.cs:6-9).Depends on:
DataSourcefromMMCA.Common.Application.Interfaces.Infrastructure.Persistence(AuditTrailSettings.cs:2), which is what puts it at Level 1, plusSystem.ComponentModel.DataAnnotationsfor[Range](AuditTrailSettings.cs:1).Concept introduced, a settings flag that gates the MODEL, not just behavior.
[Rubric §8, Data Architecture](assesses whether the mapped model and its tables are a deliberate decision) and[Rubric §30, Compliance, Privacy & Data Governance](assesses whether the system can answer "who changed this, and when"). Most feature flags in this codebase decide whether code runs; this one also decides whether a table exists.Enabledis read byAuditTrailModelContributor.AppliesTo(AuditTrailModelContributor.cs:23);ApplicationDbContextresolves the registered contributors once inOnConfiguring, keeps those that apply, and caches them in a field (ApplicationDbContext.cs:83,:332-336) that the model builder runs to map the optional tables (ApplicationDbContext.cs:675-681), so a host that leaves it false has exactly the model it had before the trail existed and its migrations never see anAuditTrailEntriestable (AuditTrailSettings.cs:10-15). That is what makes an opt-in feature genuinely free for a host that does not want it: a mapped-but-empty table would still have to be migrated. The trail is off by default because recording history is a data-governance decision an application makes deliberately (ADR-075).[Rubric §31, Cost & FinOps]: the doc onEnablednames the cost being avoided outright, a table plus a write per change (AuditTrailSettings.cs:21-25). Marking entities withIAuditedEntityis the second gate and, asAddAuditTrail's remarks put it, that is where the write volume is actually decided (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:108-110).Walkthrough: one static field and three
initproperties.SectionName = "AuditTrail"(AuditTrailSettings.cs:19), the binding key.Enabled(AuditTrailSettings.cs:26), defaulting tofalse. Read byApplicationDbContextfor the model gate (AuditTrailModelContributor.cs:23,ApplicationDbContext.cs:550-554) and re-checked by the cleanup job before it does any work (AuditTrailCleanupJob.cs:65-68).RetentionDays(AuditTrailSettings.cs:38),[Range(1, 3650)](:37), default90.AuditTrailCleanupJobturns it into a cutoff instant (AuditTrailCleanupJob.cs:70) and purges from every relational source in use, skipping Cosmos (:79-81) and expanding each source across the declared tenants (:83-86).DataSource(AuditTrailSettings.cs:46), defaultDataSource.SQLServer. Note the asymmetry the doc calls out (AuditTrailSettings.cs:40-45): rows are WRITTEN to every relational source alongside the data they describe, and this value only says which source the v1 reader looks in.AuditTrailReaderresolves it against theDefaultdatabase of that engine (AuditTrailReader.cs:66-67) and returns an empty result when the entity type is not in that model (AuditTrailReader.cs:69-72).
Why it's built this way: retention is deliberately NOT self-driving.
AddAuditTrailregistersAuditTrailCleanupJob(DependencyInjection.Jobs.cs:132) but a job only runs when the host also callsAddScheduledJobs(configuration)and setsScheduler:Enabled(DependencyInjection.Jobs.cs:101-105). Without the scheduler the trail still records everything andRetentionDaysis inert, which the settings doc states as a supported state rather than leaving it as a surprise (AuditTrailSettings.cs:32-36). Registering the job inAddAuditTrailrather than inAddScheduledJobskeeps the two features independent (DependencyInjection.Jobs.cs:129-131).Where it's used: bound with
.ValidateDataAnnotations().ValidateOnStart()atDependencyInjection.Jobs.cs:114-117, so a badRetentionDaysfails the host at startup rather than at the first sweep. Read byApplicationDbContext,AuditTrailReader(AuditTrailReader.cs:34-45) andAuditTrailCleanupJob(AuditTrailCleanupJob.cs:47-54, snapshotted at:60). Design-time tooling supplies the options object by hand so a migration can be generated with the table on or off (DesignTimeDbContextHelper.cs:178-179). The recording itself isAuditTrailSaveChangesInterceptor, registered as a singleton atDependencyInjection.Jobs.cs:121and resolved by the context withGetServiceso its absence reads as "not registered" (ApplicationDbContext.cs:541). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailModelGateTests.csandAddAuditTrailTests.cs.
KeyFix
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:888· Level 1 · record (private sealed, nested)
- What it is: a two-field pairing of a staged trail row with the key the insert has just assigned to the entity it describes: one unit of work for the store-generated-key fix-up.
- Depends on:
AuditTrailEntryandstring; nothing else. It is nested inside and private toAuditTrailSaveChangesInterceptor. - Concept introduced, resolve first, then write in batches.
[Rubric §12, Performance & Scalability](assesses whether per-item database work on a hot path is set-based): aPendingEntityKeyholds a live EF entry whose key is readable only after the insert; aKeyFixis the same row once that key has been read and compared, so the step that writes it works on plain values and never touches the tracker. Only a row whose key actually changed becomes aKeyFix, so no statement rewrites a row to the value it already holds. - Walkthrough: the positional members are
Row(the tracked trail row whoseEntityKeyis rewritten) andKey(the resolved key), declared atAuditTrailSaveChangesInterceptor.cs:888(parameter docs:885-887). Instances are built only byTakeKeyFixes(:618-630), which takes the context's pending list off theConditionalWeakTable, builds each key withBuildEntityKey, and drops any pair whose key is ordinally equal to the one captured (:627-629). The resulting array is chunked byKeyFixUpBatchSize(:552,572), each chunk is turned into oneCASEupdate byBuildKeyFixUp(:644-666, which readsRow.IdandKeyfrom every element), and the whole array is finally handed toCompleteKeyFixUp(:676-684), which syncs each tracked row to itsKeyand only then clears the capture marker. - Why it's built this way: separating "which key did the insert assign" (needs the live entry)
from "write it" (needs only values) is what lets the write be one parameterized, set-based statement
per batch. A
recordgives a readable two-name shape for pure bookkeeping, andprivate sealedkeeps it invisible. Repeating an element is harmless, which is whatBuildKeyFixUprelies on when it pads a batch to the next power of two with copies of its lastKeyFix: a duplicateWHENarm and a duplicateINvalue change nothing (remarks:639-641). - Where it's used: only inside
AuditTrailSaveChangesInterceptor. The batching it feeds is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailKeyFixUpTests.cs(Save_OfSeveralIdentityKeyedRows_RewritesEveryKeyInOneStatementat:121,Save_OfMoreRowsThanOneBatch_SplitsTheRewriteIntoBatchesat:139andSave_AfterTheFixUp_LeavesTheTrailRowsClean_SoALaterSaveIssuesNoUpdateat:155).
PendingEntityKey
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:883· Level 1 · record (private sealed, nested)
- What it is: a two-field pairing of a staged trail row with the entity entry whose primary key
the database has not assigned yet. It exists only between
SavingChangesandSavedChanges. - Depends on:
AuditTrailEntryand EF Core'sMicrosoft.EntityFrameworkCore.ChangeTracking.EntityEntry. It is nested inside and private toAuditTrailSaveChangesInterceptor. - Concept introduced, the store-generated-key fix-up.
[Rubric §8, Data Architecture](assesses whether key strategy and its consequences are handled deliberately): the trail is captured before the save, which is exactly what makes it transactional, but an entity whose key is an identity column has no key at that moment. EF holds a temporary sentinel value that would make the row unfindable by key (AuditTrailSaveChangesInterceptor.cs:315-318). Remembering the pair, then rewriting the one column after the insert, is the price of capturing early; the alternative (capturing after the save) would put the trail outside the transaction and lose the guarantee the whole design exists for. - Walkthrough: the positional members are
Row(the tracked trail row whoseEntityKeymust be rewritten) andEntry(the audited entry whose key the database assigns), declared atAuditTrailSaveChangesInterceptor.cs:883. Instances are produced byCaptureEntryonly when the entry isAddedandHasTemporaryKey(entry)returns true (AuditTrailSaveChangesInterceptor.cs:319-321, with the temporary-key test walking every primary key property at:449-466). They are accumulated into a list and parked in aConditionalWeakTable<DbContext, List<PendingEntityKey>>keyed by the context (AuditTrailSaveChangesInterceptor.cs:119,254-257), then drained inResolveGeneratedKeysAsyncorResolveGeneratedKeys(:368-396,402-429). - Why it's built this way: a
recordgives value semantics and a readable two-name shape for something that is pure bookkeeping;private sealedkeeps it invisible. Holding the list in aConditionalWeakTablerather than in an instance field is what lets the interceptor stay a singleton shared by every context without leaking state across them, and the weak keying means a context that is dropped without a save takes its pending list with it. - Where it's used: only inside
AuditTrailSaveChangesInterceptor.
AuditTrailSaveChangesInterceptor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:83· Level 8 · class (sealed)
- What it is: the EF Core save interceptor that records a field-level change history for every
entity marked
IAuditedEntity, writingAuditTrailEntryrows into the same transaction as the change they describe. - Depends on:
AuditTrailEntry,CaptureContext,PendingEntityKey,KeyFix,ApplicationDbContext,ColumnWidth(the shared truncate-to-column-width helper),IAuditedEntity,PiiAttribute,PiiRedactor,SensitiveAttribute,IAuthUser,ITwoFactorUserStateandEncryptedStringConverter(the credential and encrypted-column redaction tests),OwnedDependents,OutboxMessage,InboxMessage,ScheduledJobEntry, and the BCLTimeProvider,Activity,ConditionalWeakTableandConcurrentDictionary, plusSystem.Linq.Expressions,StrongBox<T>andBitOperationsfor the batched key fix-up. - Concept introduced, the transactional change trail.
[Rubric §6, CQRS & Event-Driven](the same interceptor-pipeline mechanic the outbox uses, applied to a different payload),[Rubric §8, Data Architecture],[Rubric §13, Observability & Operability](each row carries the ambient trace id, so a change ties back to the request or job that made it) and[Rubric §30, Compliance, Privacy & Data Governance](personal data and credentials are redacted at capture, never at read,AuditTrailSaveChangesInterceptor.cs:44-63). The class comment states the guiding rule (AuditTrailSaveChangesInterceptor.cs:25-30): a trail that can be committed without its data, or the other way round, is worse than no trail. Four mechanics are worth learning here as a set.- Opt in twice over (
AuditTrailSaveChangesInterceptor.cs:39-43): the host must callAddAuditTrail(the context resolves this interceptor withGetService, so its absence is a silent no-op,ApplicationDbContext.cs:538-543) and setAuditTrail:Enabledso the table is mapped. Then the entity must carry the marker. Nothing about the feature is on by default. - Position in the pipeline (
AuditTrailSaveChangesInterceptor.cs:32-38): registered last, afterAuditSaveChangesInterceptor, the optionalTenantSaveChangesInterceptorandDomainEventSaveChangesInterceptor(ApplicationDbContext.cs:519-543), so the values it diffs are final: the audit stamps are already written when it runs. - Correlation is the trace id, not the scoped correlation context
(
AuditTrailSaveChangesInterceptor.cs:64-75): this interceptor is a singleton and the only service provider a context carries is the root one, so a scopedICorrelationContextis not reachable from here and capturing one would be a lifetime bug. The trace id is ambient and is the same valueCorrelationIdMiddlewarefalls back to when a request carries noX-Correlation-IDheader. A caller-supplied header value is therefore NOT recorded today. - Tenant is read off the context (
AuditTrailSaveChangesInterceptor.cs:76-80), through the live accessor the scoped context factory assigns (ApplicationDbContext.cs:150), so it does reach the interceptor where a scoped service would not.
- Opt in twice over (
- Walkthrough:
- Constants (
AuditTrailSaveChangesInterceptor.cs:85-113): the three operation names, the four column widths (MaxEntityTypeLength256,MaxKeyLength128,MaxCorrelationIdLength64,MaxTenantIdLength64), the|composite-key separator, andKeyFixUpBatchSize256 (:113), the most trail rows one key fix-up statement rewrites: each row costs two parameters in theCASEand one in theINlist, so a full batch stays well under SQL Server's 2100-parameter cap (:108-112). The column widths match the model mapping inAuditTrailModelContributor.Configureexactly (AuditTrailModelContributor.cs:31-36). - Static state (
AuditTrailSaveChangesInterceptor.cs:115-160): twoConditionalWeakTables keyed by context (pending key fix-ups, and a marker for "a capture staged rows but the save has not finished"), aConcurrentDictionarycaching the PII verdict per (declaring type, property name), a secondConcurrentDictionary(CredentialCache,:140) caching each CLR type's credential property names, theCredentialInterfacesarray naming the two interfaces whose members carry credential material,IAuthUserandITwoFactorUserState(:146), and aHashSet<Type>of the framework's own bookkeeping entities. That last set is guarded by CLR type, not by the absence of the marker, which is what keeps the trail from recording its own rows in an unbounded feedback loop and keeps the outbox, inbox and job tables out of a history nobody asked for (AuditTrailSaveChangesInterceptor.cs:148-160).IsFrameworkEntity(Type)(:212) is theinternalwindow onto that set, which is both howShouldAuditconsults it and how a test can assert the exclusion list directly. - The four overrides (
AuditTrailSaveChangesInterceptor.cs:162-204):SavingChangesAsyncandSavingChangesboth callCaptureChanges;SavedChangesAsyncandSavedChangesboth run the key fix-up. Each pattern-matcheseventData.Context is ApplicationDbContextfirst, so a foreign context passes straight through. CaptureChanges(AuditTrailSaveChangesInterceptor.cs:218-260): the first statement is the cheap double gate,context.Model.FindEntityType(typeof(AuditTrailEntry)) is null(:220-226), which covers both a host that never opted in and Cosmos (which skips relational tables), becauseSet<AuditTrailEntry>()would throw for both. Then it discards an abandoned capture, builds oneCaptureContext, snapshotsChangeTracker.Entries().Where(ShouldAudit).ToArray()(:238, materialized before adding, because enumerating the tracker lazily while adding to it would throw), and captures each entry.ShouldAuditandIsBeingWritten(AuditTrailSaveChangesInterceptor.cs:267-279): the entity carries the marker, is not a framework bookkeeping type, and the save actually writes its row.IsBeingWrittenis true forAdded,ModifiedandDeleted, and also for anUnchangedowner whose owned value object changed (it asksOwnedDependents.HaveChanges(entry),:276), because EF tracks an owned edit on the owned entry and leaves the owner itselfUnchanged.CaptureEntry(AuditTrailSaveChangesInterceptor.cs:289-322): aModifiedorUnchangedentry (:297) delegates to the per-property diff and then to the owned-value diff; anAddedorDeletedentry writes one summary row and then, only when the insert's key is still temporary, returns aPendingEntityKey, whose key is rewritten after the insert always inside the save's transaction (comment at:315-318).CaptureModifiedProperties(AuditTrailSaveChangesInterceptor.cs:331-373): one row per property that isIsModifiedand whose value actually differs. A property EF flagged as modified but whose value is unchanged (the whole-entityUpdateidiom) writes nothing (:352-355). A concurrency token is skipped outright (:345): on PostgreSQL and SQLite the audit interceptor writes a freshRowVersionon every update, so it would otherwise add a bookkeeping row to every change.PiiRedactor.HasPii(entry.Metadata.ClrType)is checked once per entity so a type with no personal data skips the per-property attribute lookup entirely (:340), and the entity's credential names are resolved once beside it (:341). A redacted property recordsPiiRedactor.RedactedTokenon both sides (:357,364-365); what counts as redacted isIsRedacted, described under Helpers.CaptureOwnedChangesandCaptureOwnedReference(AuditTrailSaveChangesInterceptor.cs:386-408,:410-458): one row per changed column of each owned value object the owner carries (anOwnsOneaddress, anOwnsMoneyamount), namedNavigation.Property(:448) and recorded under the owner's type and key. It walksentry.References, keeps owned targets in stateAddedorModified(:395-396), and diffs each value column with the sameValuesEqual, PII andFormatValuerules as the plain path. A replaced instance arrives as a newAddedowned entry beside theDeletedone it replaces, soFindReplacedOwnedEntry(:467-490) matches on owned entity type and shared key and the previous value is read from thatDeletedentry.IsOwnedValueColumn(:464-465) excludes the shadow key, the foreign key to the owner and concurrency tokens. A[Pii]navigation redacts the whole owned value:CaptureOwnedChangespassesIsPiiMember(reference.Metadata.PropertyInfo)for the owner's navigation (:401), and when it is true every value column of that owned entry records the redaction token (navigationIsPii || IsRedacted(...),:442, remarks at:413-417), whether or not the owned type marks its own members (an[Pii] Addresson a customer). Clearing an optional owned reference tonullleaves no owned entry and is not recorded (the remarks at:383-384).DiscardAbandonedCapture(AuditTrailSaveChangesInterceptor.cs:510-531): the retry-safety mechanic. An execution strategy that retries a failed save re-runsSavingChangesagainst a tracker that still holds the previous attempt'sAddedrows, so without this one transient SQL fault writes the trail twice. It only fires when the marker is present (a completed save leaves noneAdded), because discarding unconditionally would also throw away trail rows a caller added deliberately.ResolveGeneratedKeysAsyncandResolveGeneratedKeys(AuditTrailSaveChangesInterceptor.cs:548-562,568-581): the key fix-up, set-based (summary:533-542).TakeKeyFixes(:618-630) takes the context's pending list, pairs each row with the key the insert assigned as aKeyFixand drops any whose key did not change. The fixes are chunked byKeyFixUpBatchSizeand each chunk becomes ONEExecuteUpdaterestricted to the chunk's ids whose value isCASE WHEN Id = @id1 THEN @key1 ... ELSE EntityKey END(:552-559), so a bulk insert of N audited identity-keyed rows costs N / 256 statements rather than N.BuildKeyFixUp(:644-666) builds that expression: it pads the chunk to the next power of two by repeating its last row (:646-651), which bounds the distinct statement shapes, and so the compiled queries in EF's cache, to a handful, and every id and key passes throughAsSqlParameter(:669-670, a field read off aStrongBox<T>) so it reaches SQL as a parameter, never a literal, and the statement text is reused (remarks:636-643). LikeOutboxFinalizerit bypasses the change tracker and the interceptor pipeline. It always runs inside the save's transaction: the caller's when one is open, otherwise the oneApplicationDbContextopens for exactly this case, so a trail row and its key commit together.HasPendingGeneratedKeys(:591-597) is theinternalquestion the context asks before a save with no transaction of its own, and its answer mirrors whatCaptureChangeswill remember as pending (ApplicationDbContext.cs:286-292, consulted at:235and:271). The context then saves inside a transaction opened within the execution strategy, with acceptance deferred until the commit, and never retries the commit itself (a commit failure surfaces asTransactionCommitAmbiguousException,ApplicationDbContext.cs:294-315).CompleteKeyFixUp(:676-684) runsSyncTrackedKeyper fix and only afterwards removes the capture marker, so a fix-up that throws leaves the marker and the next capture discards the staged rows rather than writing them twice (remarks:543-547). For a failure pastSavedChanges(the commit of that opened transaction, or anything after the fix-up),MarkCaptureAbandoned(:599-612) re-arms the marker wheneverAddedtrail rows remain, and the context calls it from every failed attempt (ApplicationDbContext.cs:469-473). BecauseExecuteUpdatebypasses the tracker,SyncTrackedKey(:692-707, summary at:685-691) assigns the resolved key to the tracked instance. A row stillAdded(the deferred-acceptance save) stops there (:697-702), because accepting it after the commit snapshots that value; otherwise it writes the same value into the snapshot, so the CLR assignment is not detected as a change and a later save on the same context does not re-issue the update. The ordering there is load-bearing: writingOriginalValue(:705) must precede clearingIsModified(:706), because clearing the flag reverts the current value to the original.- Helpers:
AddRow(:492-502, mutation isAddonly, because the save runs with automatic change detection off),HasTemporaryKey(:709-730),BuildEntityKey(:732-749, a keyless entity yields an empty string rather than throwing),IsRedacted(:758-761, see below),IsPiiProperty(:768, now a one-line delegation toIsPiiMember) andIsPiiMember(:775-788, shared by a mapped column and by the owner's navigation to an owned type; a member with noPropertyInfo, a shadow property or a field-only navigation, can never be personal data; the verdict uses the staticAttribute.IsDefined(propertyInfo, typeof(PiiAttribute), inherit: true)at:786, because thePropertyInfo.IsDefinedinstance method ignoresinheritfor properties, and only the static form walks an override back to its base declaration, matching howPiiRedactordecides, comment at:784-785),CredentialPropertyNames(:796-823),IsAuditedStateandIsAuditedStateGetter(:830-835),FormatValue(:843-848,CultureInfo.InvariantCultureon purpose, so a trail read years later or on a differently localized replica shows the value that was written; abyte[]such as a hash or salt renders as hexadecimal viaConvert.ToHexStringat:846, because the invariantConvert.ToStringwould record its type name on both sides and lose the change) andValuesEqual(:854-867, byte arrays such as row versions are compared by content, since reference equality would report every save as a change). IsRedactedandCredentialPropertyNames(:758-761,:796-823): redaction is wider than the[Pii]marker. A changed property records the redaction token when any of three tests holds: it is personal data (typeHasPii && IsPiiProperty), its name is in the type's credential set, or its value converter is anEncryptedStringConverter(:761). The last needs no marker, because the change tracker hands the interceptor the model-side (decrypted) value of a column stored through that converter, so recording it would put in clear text exactly what the column encrypts (summary:751-757). The credential set, computed once per CLR type and cached inCredentialCache(:140), is, for each of theCredentialInterfacesthe type implements (:802), the members implementing it (resolved throughGetInterfaceMap, so an inherited implementation is found,:804-809; an explicit implementation is a private, differently named property EF does not map, so the interface member's own names are added too,:811-815), plus every property carryingSensitiveAttribute(:818-820). One member is deliberately left out:IsAuditedState(:830-831) exemptsITwoFactorUserState.IsTwoFactorEnabled, filtered from the interface map by its getter (IsAuditedStateGetter,:834-835, used at:807) and from the name list at:814, because whether the second factor is on is state, not secret material, and is exactly what an administrator reviewing an account's history needs to see change (summary:825-829). So the password hash and salt and the two-factor secret and recovery-code hashes are redacted while the on/off flag stays readable. An empty set is the cheap common case. The same gate applies to owned columns (CaptureOwnedReferencecalls the sameIsRedacted,:442).- Column-width truncation is not a private method on this type: every call
site (the correlation id and tenant id in
CaptureChanges, the entity type inCaptureEntry, the property name inCaptureModifiedPropertiesat:363, the owned column name inCaptureOwnedReferenceat:448, and the composite key inBuildEntityKeyat:748) goes through the sharedColumnWidth.Truncatehelper.
- Constants (
- Why it's built this way: ADR-075 chose the interceptor over a repository decorator (which sees intent, not the tracker's diff), an application handler (which sees the command, not the properties EF marked modified) and a database trigger (which sees the diff and nothing else: no user, no correlation id, no PII knowledge). Committing in the caller's transaction is the outbox mechanic of ADR-003 applied to a different payload, and redacting at capture is what keeps the trail compatible with ADR-005.
- Where it's used: registered as a singleton by
AddAuditTrail(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:120-122, singleton for the same reason as the other two save interceptors: stateless, with per-save state in aConditionalWeakTablekeyed by context), added to the EF pipeline inApplicationDbContext.OnConfiguring(ApplicationDbContext.cs:538-543), and registered in the design-time pipeline too sodotnet efmatches runtime (DesignTimeDbContextHelper,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:178-180). Behavior is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailSaveChangesInterceptorTests.cs,AuditTrailModelGateTests.cs,AuditTrailOwnedAndTwoFactorRedactionTests.cs(the[Pii]navigation and two-factor credential redaction) andAuditTrailKeyFixUpTests.cs(the transaction the context opens for the fix-up, rollback and retry of a failed attempt, and the batched rewrite). Hosts opting in today include MMCA.Helpdesk (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:78), all three MMCA.Store services (Identity.Service/Program.cs:188,Sales.Service/Program.cs:206,Catalog.Service/Program.cs:210) and all three MMCA.ADC services (Engagement.Service/Program.cs:197,Identity.Service/Program.cs:232,Conference.Service/Program.cs:296). - Caveats / not-in-source: a caller-supplied
X-Correlation-IDis not recorded; honoring it would need a live accessor on the context assigned by the scoped factory, the shape multi-tenancy introduced forTenantId(AuditTrailSaveChangesInterceptor.cs:72-74). Whether that will be done is Not determinable from source.
AuditTrailModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailModelContributor.cs:17· Level 9 · class (internal sealed)
- What it is: the
IModelContributorthat maps theAuditTrailEntrytable into a context's EF model when, and only when,AuditTrail:Enabledis true. It is the model half ofAddAuditTrail: the interceptor writes the rows, this type decides whether there is a table to write them to. - Depends on:
IModelContributorandModelContributorPhase(the contract and the ordering it reports),AuditTrailSettingsviaIOptions<>(the primary constructor,AuditTrailModelContributor.cs:17),PhysicalDataSourceandDataSource(the parameters ofAppliesToandConfigure), andAuditTrailEntry(the entity it maps). - Concept introduced, an optional framework table contributed rather than hard-coded.
[Rubric §8, Data Architecture](assesses whether the mapped model is a deliberate decision per host) and[Rubric §31, Cost & FinOps](a host that never opts in carries no table and no migration for it). The class comment states the one condition and where it applies (AuditTrailModelContributor.cs:9-15): unlike the scheduler's job table, which lives on one host-scoped database, the trail table belongs in EVERY relational source, because a trail row must commit in the same transaction as the change it describes and a transaction does not span databases (the outbox precedent). SoAppliesToignores the source it is handed and returnssettings.Value.Enabled(AuditTrailModelContributor.cs:23). The context does the rest: it collects contributors only for a relational engine (Cosmos never runs the baseOnModelCreating), filters them throughAppliesToagainst its own physical source, and orders them by phase (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:547-554). - Walkthrough: three members.
Phase(AuditTrailModelContributor.cs:20):ModelContributorPhase.AfterEntityPasses, so the mapping runs after the soft-delete filter and concurrency-token passes (ApplicationDbContext.cs:664-666). That is correct for this entity, which is deliberately not anIAuditableEntityand must not pick up either.AppliesTo(PhysicalDataSource)(AuditTrailModelContributor.cs:23): theAuditTrail:Enabledflag, nothing else.Configure(ModelBuilder, DataSource)(AuditTrailModelContributor.cs:26-48): maps the entity todbo.AuditTrailEntrieswithIdas key (:29-30),EntityTyperequired at 256 non-unicode characters,EntityKeyrequired at 128,PropertyNameat 128 non-unicode,Operationrequired at 16 non-unicode, andCorrelationIdandTenantIdat 64 non-unicode (:31-36). These widths are the onesAuditTrailSaveChangesInterceptortruncates to. Two indexes follow:IX_AuditTrailEntries_Entityover(EntityType, EntityKey, ChangedOn)for the read path, carrying the whole predicate plus the sort thatAuditTrailReaderissues (:38-41), andIX_AuditTrailEntries_ChangedOnfor the retention sweep, because the read index leads withEntityTypeand without a second index the nightlyAuditTrailCleanupJobwould scan the table (:43-47). Theengineparameter is unused: the mapping is identical on every relational engine.
- Why it's built this way:
ADR-148
moved each optional framework table out of
ApplicationDbContextand into a contributor that the feature's ownAddXcall registers, so the context no longer needs to know every optional feature. Because the contributor set changes the model, it joins the model cache key (pinned byModelCacheKeyGateTests.cs:66), so two hosts or two sources with different contributors never share a cached model. - Where it's used: registered by
AddAuditTrailasTryAddEnumerable(ServiceDescriptor.Singleton<IModelContributor, AuditTrailModelContributor>())(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:123-125), and added at design time whenEnableAuditTrailis set, over settings withEnabled = true, sodotnet efsees the same table the runtime model has (DesignTimeDbContextHelper,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:194-195). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailModelGateTests.cs:90,DependencyInjectionModelContributorTests.cs:35(theAddAuditTrailto contributor pairing) andMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/ModelCacheKeyGateTests.cs:66.
AuditTrailReader
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailReader.cs:34· Level 10 · class (internal sealed)
- What it is: the read side of the trail, and the only implementation of
IAuditTrailReader. It returns one entity's change history, newest first, as a paged list ofAuditHistoryEntryDTO(AuditTrailReader.cs:48). - Depends on:
IAuditTrailReader,IDbContextFactory,IDataSourceResolver,DataSourceKey,AuditTrailEntry,AuditHistoryEntryDTOandAuditTrailSettingsviaIOptions<>(AuditTrailReader.cs:34-45). - Concept introduced, projecting to a DTO inside the query rather than after it.
[Rubric §9, API & Contract Design](the Application-layer contract returns a Shared-layer DTO, never the persistence entity) and[Rubric §12, Performance & Scalability](theSelectis part of the SQL, so only the projected columns cross the wire, andAsNoTrackingkeeps the rows out of the change tracker). The ordering isChangedOndescending withIdas the tie-break (AuditTrailReader.cs:76-77), which matters because every row of one save shares an identicalChangedOn: without the second key, paging over a save's worth of rows would not be stable. - Walkthrough:
GetForEntityAsync(entityType, entityKey, page = 1, pageSize = 50, ct)(AuditTrailReader.cs:48-53).- Paging guards (
AuditTrailReader.cs:55-64): a page below 1 is coerced to 1 rather than rejected (:55), and the page size is clamped into 1 toMaxPageSize(:56), a private constant of 500 (:43) that its comment ties to the same capOutboxAdministration.MaxPageSizeapplies to its own paged read (:39-42). The offset is computed inlong(:60), because(page - 1) * pageSizeoverflowsintfor a large page number and some engines read the wrapped negative offset as 0, which would hand back the first page (comment at:58-59); an offset pastint.MaxValuereturns an empty list (:61-64). A bad caller therefore gets a bounded page or nothing, never an exception and never a silently wrong page. - Source resolution (
AuditTrailReader.cs:66-67): resolves theDefaultdatabase of the engine named byAuditTrail:DataSource(defaulting to SQL Server,AuditTrailSettings.cs:46) and asks the context factory for it. - Model gate (
AuditTrailReader.cs:69-72): returns an empty list when the trail entity is not in the model. The comment gives the reason (AuditTrailReader.cs:25-29): the read surface is registered byAddAuditTrail, which a host may call before flippingAuditTrail:Enabledper environment, so "not enabled" must read as "no history", not as an exception. - The query (
AuditTrailReader.cs:74-94):AsNoTracking, filtered onEntityTypeandEntityKey(exactly the leading columns ofIX_AuditTrailEntries_Entity,AuditTrailModelContributor.cs:40-41), ordered, skipped by the checked offset (:78) and taken (:79), then projected column by column intoAuditHistoryEntryDTO(AuditTrailReader.cs:80-92).TenantIdis not projected, because the DTO has no such member: it declaresIdthroughCorrelationIdand stops there (MMCA.Common/Source/Core/MMCA.Common.Shared/Auditing/AuditHistoryEntryDTO.cs:12-49).
- Paging guards (
- Why it's built this way: the DTO stops the persistence entity from leaking into the Application
contract, and matching the query's predicate and sort to the shipped index is why that index carries
the whole predicate plus the sort rather than just the key
(
AuditTrailModelContributor.cs:38-41). - Where it's used: registered as the scoped
IAuditTrailReaderbyAddAuditTrail(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:127). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailReaderTests.csand the registration byAddAuditTrailTests.cs:64,89. A source search across the workspace finds no application or UI consumer of the interface today: it is a shipped read surface that hosts can inject, not a wired-up screen. - Caveats / not-in-source: the class documents its own v1 limitation
(
AuditTrailReader.cs:15-24). Trail rows are written to whichever database holds the entity that changed (that is what makes the write atomic), so a host that splits its modules across several databases has several trail tables, and this reader queries exactly one of them: theDefaultdatabase of the configured engine. For a monolith, where every source collapses ontoDefault, that is the whole trail. Reading another module's history would need a per-source overload, which the comment says was deliberately deferred rather than guessed at.
AuditTrailWriter
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailWriter.cs:36· Level 10 · class (internal sealed)
- What it is: the only implementation of
IAuditTrailWriter, the explicit write side of the trail. It records an event that changed no data (an access, such as a personal-data export) as oneAuditTrailEntryrow per call, in the databaseAuditTrailReaderreads, so the event shows in that entity's history beside its recorded changes (AuditTrailWriter.cs:11-14). - Depends on:
IAuditTrailWriter,IDbContextFactory,IDataSourceResolver,AuditTrailSettingsviaIOptions<>andTimeProvider(the primary constructor,AuditTrailWriter.cs:36-40), plusDataSourceKey,AuditTrailEntry,ColumnWidthand the column-width constants ofAuditTrailSaveChangesInterceptor(AuditTrailSaveChangesInterceptor.cs:95,98,101,104, allinternal const). - Concept introduced, the explicit counterpart to an automatic trail.
[Rubric §30, Compliance, Privacy & Data Governance](assesses whether access to personal data leaves a record, not only changes to it). The interceptor sees only what a save writes, so an event that writes nothing (a read of someone's data) would never appear in a history built from saves alone. The interface comment states the boundary (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IAuditTrailWriter.cs:9-15): this records the same identifying columns only (entity type, key, operation, who and when) and no property name and no before or after value, so it can never become a copy of the data it describes. - Walkthrough: one constant, one snapshotted field, one method.
MaxOperationLength = 16(AuditTrailWriter.cs:43), the width the model contributor mapsOperationto (AuditTrailModelContributor.cs:34)._settingsis snapshotted fromoptions.Value(:45).RecordAsync(entityType, entityKey, operation, actorId, ct)(AuditTrailWriter.cs:48-53). Argument guards first (:55-57): a blank entity type or operation and a null key throw. An operation longer than 16 characters throwsArgumentOutOfRangeExceptionrather than being truncated, because a name too long for the column is a programming error (:59-66).- Inert until the trail is on (
AuditTrailWriter.cs:16-22): it returns without resolving a context whenAuditTrail:Enabledis false (:68-71), the value an unbound section yields in a host that never calledAddAuditTrail. Otherwise it resolves theDefaultdatabase of the engine named byAuditTrail:DataSource(:73-74), the same target the reader queries, and returns again when the trail entity is not in that model (Cosmos, or no model contributor,:76-79), the same model check the interceptor and the reader make. - The row (
AuditTrailWriter.cs:82-91): shaped like the interceptor's summary rows (noPropertyName, no values) and stamped the same way:EntityTypeandEntityKeytruncated throughColumnWidth.Truncateto the interceptor's widths,ChangedOnfromTimeProvider,CorrelationIdfrom the ambientActivity.Currenttrace id, andTenantIdfromcontext.CurrentTenantId(:84-90). - The save (
AuditTrailWriter.cs:93):SaveChangesAsync(actorId, ct), the user-stamping overload (ApplicationDbContext.cs:206-212). The remarks spell out the consequence (AuditTrailWriter.cs:26-29): the context is the scope's shared one, so anything else pending on it is flushed by the same save, and inside an open transaction the row commits or rolls back with it.
- Why it's built this way: registering the writer unconditionally lets a handler depend on it
without knowing whether the host opted into the trail, and the in-method gates make that dependency
free when it did not. Writing to the reader's database rather than to the database of the entity's
module is what makes "what is written here is what the history endpoint shows" true
(
IAuditTrailWriter.cs:17-21). - Where it's used: registered by
AddInfrastructure, notAddAuditTrail, asTryAddScoped<IAuditTrailWriter, AuditTrailWriter>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:134-137, the comment giving the always-registered reason). Its one caller in source isExportUserDataHandlerBase<TUser, TQuery>, which records anExportedrow (ExportedAuditOperation,MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:80) against the exported account before the package is handed back (ExportUserDataHandlerBase.cs:139-142, rule at:33-39: a failure to write the record fails the export). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailWriterTests.cs:20and the scoped registration byDependencyInjectionInfrastructureTests.cs:78.
AuditTrailCleanupJob
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.AuditTrail·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailCleanupJob.cs:45· Level 13 · class (internal sealed partial)
- What it is: the framework's own recurring job. It purges
AuditTrailEntryrows older than the configured retention window from every relational database that holds a trail table, in batches. - Depends on:
IScheduledJob(the contract it implements),IDbContextFactory,FrameworkTableTargets(which databases hold the table),AuditTrailSettingsviaIOptions<>,TenantDataSourceTargets(forCreateTenantScope) plusTenantDataSourceTarget,BatchedDelete(the shared batched retention delete),TimeProvider,IServiceScopeFactoryandILogger<T>(AuditTrailCleanupJob.cs:45-51). - Concept introduced, retention as a first-class part of a history feature.
[Rubric §30, Compliance, Privacy & Data Governance](assesses whether retained data has a bounded lifetime),[Rubric §31, Cost & FinOps](assesses whether unbounded growth is designed out) and[Rubric §29, Resilience & Business Continuity](a first sweep over a neglected table must not become one enormous transaction). The class comment makes the argument (AuditTrailCleanupJob.cs:16-20): a change trail grows monotonically and stores values that may describe a data subject, so a retention window is not housekeeping, it is what keeps the table from being both a cost centre and a data-protection liability. It also records the honest limitation (AuditTrailCleanupJob.cs:21-26):AddAuditTrailregisters the job, but a job with no runner never executes, so the host must also callAddScheduledJobsand setScheduler:Enabled. A host that records the trail without the scheduler is fully supported and keeps recording; pruning is then the operator's job. - Walkthrough:
- Constructor (
AuditTrailCleanupJob.cs:45-51): the last parameter, the scope factory, is optional and defaults tonull, because a host without tenancy never leaves the job's own scope. Tenancy settings are no longer a parameter here: tenant discovery moved intoFrameworkTableTargets._settingsis snapshotted fromoptions.Value(:53), andRetentionDaysdefaults to 90 with a[Range(1, 3650)]guard (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSettings.cs:36-37). NameandCronExpression(AuditTrailCleanupJob.cs:56,60):"audit-trail-cleanup", daily at0 3 * * *(03:00 UTC), chosen to sit off the daily peak for every time zone the framework runs in (:59).ExecuteAsync(AuditTrailCleanupJob.cs:63-76): returns immediately whenAuditTrail:Enabledis false (:65-68), computes the cutoff as now minusRetentionDays(:70), then sweeps every targettableTargets.Relational()returns (:72-75). That call (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:43-44) takes every relational physical source backing a registered entity, deduplicates it and expands it per tenant that keeps its own copy, skipping Cosmos; it is the one answer the outbox processor, the internal-command processor, both cleanup services, both operator surfaces and this sweep share, rather than each re-deriving it from the registry, the resolver and the tenancy settings (FrameworkTableTargets.cs:16-18).PurgeTargetAsync(AuditTrailCleanupJob.cs:83-100): the shared database is swept on the job's own scope; a tenant that keeps its own database gets a fresh scope fromTenantDataSourceTargets.CreateTenantScope(:94), the shared extension that setsITenantContextbefore the context is asked for, because the scoped context factory binds one database per scope and the job's scope is already bound to the shared one (doc at:78-82).PurgeWithFactoryAsync(AuditTrailCleanupJob.cs:103-131): resolves the target's context and re-checks the model for the trail entity (:113-116, comment at:111-112), returning a completed task when it is absent. Cosmos is already excluded, but a relational source can still lack the table when the host disabled the trail after writing it, so the model, not the configuration, is the authority. It is no longerasync: it hands the sweep to the sharedBatchedDelete.DeleteAsynchelper (:119-130) with the retention predicateChangedOn < cutoff,ChangedOnas the ordering column, and a report callback.- The batching lives in that helper, not in this class
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Retention/BatchedDelete.cs:39-60): it reads up toBatchSize(1000,BatchedDelete.cs:18) ids, then deletes those ids, because every relational engine translates anINlist while a limitedDELETEis not universally supported (BatchedDelete.cs:8-14). Cancellation is observed between batches, and the report callback is called exactly once with the total actually removed, from afinally, so a sweep that throws or is cancelled mid-batch still reports what it destroyed (BatchedDelete.cs:32-35,56-59). The helper also refuses anIAuditableEntityrow type outright (BatchedDelete.cs:86-90), which the trail entry is not. The outbox, inbox, internal-command and refresh-session sweeps call the same helper. - Logging (
AuditTrailCleanupJob.cs:133-134): a source-generatedLoggerMessageemitted from the report callback only when a sweep actually removed rows (:125-128), so a quiet night logs nothing.
- Constructor (
- Why it's built this way: registering the job in
AddAuditTrailrather than inAddScheduledJobskeeps the two features independent, which the DI comment states outright (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:129-131): the trail can be enabled without the scheduler and the scheduler without the trail. Set-based batched deletion is the same discipline the outbox retention sweep uses, for the same reason, and both now share one implementation inBatchedDeleterather than each carrying its own loop; taking its target list fromFrameworkTableTargetsmeans this sweep visits exactly the databases the other framework-table sweeps visit. - Where it's used: registered through
AddScheduledJob<AuditTrailCleanupJob>()insideAddAuditTrail(DependencyInjection.Jobs.cs:132, and that helper does aTryAddScopedof the concrete type plus aTryAddEnumerableofIScheduledJobat:74-75), and executed byScheduledJobRunnerwhen the host runs the scheduler. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailCleanupJobTests.cs.
SignInChainRow
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:382· Level 0 · class (internal sealed, nested inEFRefreshSessionStore)
- What it is: the scalar row the sign-in history's first query projects into: one sign-in and
the span of instants its sessions cover. It is nested inside
EFRefreshSessionStoreand documented as one row ofSignInChainsQuery(EFRefreshSessionStore.cs:381-392). - Depends on: nothing beyond BCL
GuidandDateTime. - Concept introduced, project to a named scalar type so the grouping stays in the database.
[Rubric §12, Performance and Scalability]assesses whether a read is bounded by the page it returns rather than by the rows it scans.SignInChainsQuerygroups one user'sRefreshSessionsrows bySignInId, orders and limits the groups, and selectsnew SignInChainRow { ... }from each (EFRefreshSessionStore.cs:158-173), so EF Core translates the MIN and MAX into SQL and materializes one small object per sign-in instead of every session row of a long rotation chain. A named class withinitsetters, rather than an anonymous type, is what lets that query be its owninternal static IQueryable<SignInChainRow>method. - Walkthrough
SignInId(EFRefreshSessionStore.cs:385) isGuid?only because the column is nullable; the query filtersSignInId != null(:163), so it is never null here, as the member doc says (:362).StartedAt(:366) is theCreatedAtof the sign-in's earliest retained session,g.Min(s => s.CreatedAt)(:171).LastActiveAt(:369) is theCreatedAtof its newest session,g.Max(s => s.CreatedAt)(:172), and is the instantSignInHeadsQueryseeks on to load each sign-in's head row (:115-116).
- Why it's built this way: the type carries three scalars between the statements of
GetRecentSignInsAsyncand nothing else; nesting it and keeping itinternalkeeps the projection out of the public surface. - Where it's used: only inside the defining file: produced by
SignInChainsQuery(EFRefreshSessionStore.cs:158) and consumed byGetRecentSignInsAsync(:105-132), which matches each row to its head and builds aRefreshSessionSignInfrom it (:130).
PermissionGrantRefreshService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PermissionGrantRefreshService.cs:31· Level 1 · class (internal sealed partial,PeriodicBackgroundService)
- What it is: the background loop that keeps
PermissionGrantCachewarm. It callsRefreshAsyncon an interval for the lifetime of the host, so the cache never goes stale by more than onePermissionGrants:CacheSecondswindow (PermissionGrantRefreshService.cs:31-63). - Depends on:
IPermissionGrantCache(the interface it refreshes through, not the concretePermissionGrantCachedirectly),IOptions<PermissionGrantSettings>,ILogger<PermissionGrantRefreshService>, an optionalTimeProvider, andPeriodicBackgroundServiceit extends (PermissionGrantRefreshService.cs:31-36). - Concept introduced, a cache that survives its own reload failing.
[Rubric §29, Resilience & Business Continuity](assesses whether a background loop degrades rather than crashes the host) and[Rubric §13, Observability & Operability](a failed reload is logged, not silent). The class remarks state the direction deliberately (PermissionGrantRefreshService.cs:13-17): a failed load is logged and retried, never fatal, because a database blip must degrade authorization to "no stored grants" rather than take the host down. - Walkthrough: the whole interval loop, its cancellation handling and its catch-log-continue
behavior live once in
PeriodicBackgroundService; this type supplies only four overrides.Intervalreturns_settings.CacheSeconds(PermissionGrantRefreshService.cs:41).StartupDelayreturnsTimeSpan.Zero(:44-47): the snapshot is primed immediately at startup, because until the first load authorization sees no stored grants at all, unlikeRefreshSessionCleanupService, whose first sweep waits a full interval.ExecuteCycleAsyncis one line,cache.RefreshAsync(stoppingToken)(:54), andLogCycleFailureroutes a cycle's exception to the source-generatedLogRefreshFailedmessage (:57,:59-62); the base class is what turns a thrown exception there into "log and keep looping" rather than a host crash. - Why it's built this way: registering it through
TryAddEnumerablerather thanAddHostedService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:208-211) is what keeps two modules callingAddStoredPermissionGrantsfrom starting two refresh loops in one process, the same idempotent-registration disciplineRefreshSessionCleanupServiceandAuditTrailCleanupJobuse for their own recurring work. Catching broadly and logging rather than crashing follows ADR-116: a stored-grant feature that takes the host down on a transient database fault would be worse than the fallback it exists to layer over. - Where it's used: registered as a singleton
IHostedServicebyAddStoredPermissionGrants(DependencyInjection.Auth.cs:210-211), started and stopped by the generic host alongside every otherBackgroundService. Its only collaborator isPermissionGrantCachethroughIPermissionGrantCache.RefreshAsync.
PasskeyCredentialModelBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PasskeyCredentialModelBuilderExtensions.cs:17· Level 4 · class (public static)
- What it is: the single place the
PasskeyCredentialstable is mapped. One extension method,ApplyPasskeyCredentialConfiguration(this ModelBuilder, string? schema = "dbo"), configures thePasskeyCredentialentity: table, key, column widths and the two indexes the WebAuthn flows read through (PasskeyCredentialModelBuilderExtensions.cs:17-61). - Depends on:
PasskeyCredentialfromMMCA.Common.Domain.Auth(including itsCredentialIdMaxLength,PublicKeyMaxLength,NameMaxLengthandTransportsMaxLengthconstants) and EF Core'sModelBuilder. - Concept introduced: none new. This is the opt-in framework table of
RefreshSessionModelBuilderExtensionsapplied to passkeys, under[Rubric §8, Data Architecture]and[Rubric §11, Security](assesses whether credential storage is designed rather than incidental). The class doc names its precedent:ApplicationDbContextapplies it to the one context whose source is named byPasskeys:DataSourceName, and only whilePasskeys:Enabledis true, so a host that never opts in keeps a byte-identical model (PasskeyCredentialModelBuilderExtensions.cs:11-16). - Walkthrough
- Three public constants:
TableName = "PasskeyCredentials"(PasskeyCredentialModelBuilderExtensions.cs:20),CredentialIdIndexName = "IX_PasskeyCredentials_CredentialId"(:18) andUserIdIndexName = "IX_PasskeyCredentials_UserId"(:21). - The method null-guards (
:29), maps the table with the caller's schema defaulting todbo(:33), keys onIdand marks itValueGeneratedNever(:34-35), so the domain assigns the key. CredentialId,PublicKeyandNameareIsRequiredand bounded by the domain constants;Transportsis bounded but optional (:39-42). The comment at:37-38gives the reason the binary credential id is bounded at all: the unique index has to fit the engine's key-size limit, and WebAuthn caps a credential id at 1023 bytes.SignCount,CreatedOnandLastUsedOntake EF defaults (:43-45).- The unique index on
CredentialId(:48) is the sign-in path: an assertion names the credential, never the account (:47). The non-unique index onUserId(:51) is the list path, one account's passkeys (:50). - The builder is returned for chaining (
:54).
- Three public constants:
- Why it's built this way: ADR-139
makes passkeys an opt-in sign-in method, so the table must not appear in a model that did not opt in;
a callable extension method behind a context gate is how the framework already expresses that for
refresh sessions and view-as grants. The two indexes answer exactly the two lookups
EFPasskeyCredentialStoremakes by something other than the key,FindByCredentialIdAsyncandListForUserAsync. - Where it's used: called by
PasskeyCredentialModelContributorfromConfigure(PasskeyCredentialModelBuilderExtensions.cs:83-84), whichApplicationDbContextruns fromOnModelCreatingin itsAfterEntityPassespass (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:664-666) only on a source whereAppliesToholds:Passkeys:EnabledAND this instance's physical source name equalsPasskeys:DataSourceName(PasskeyCredentialModelBuilderExtensions.cs:78-80). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/Passkeys/PasskeyModelGateTests.cs.
PermissionGrantModelBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PermissionGrantModelBuilderExtensions.cs:23· Level 4 · class (public static)
- What it is: the single place the
PermissionGrantstable is mapped. One extension method,ApplyPermissionGrantConfiguration(this ModelBuilder, string? schema = "dbo"), configures thePermissionGrantentity: table, key, column widths, and the unique index that makes a grant idempotent (PermissionGrantModelBuilderExtensions.cs:23-72). - Depends on:
PermissionGrantfromMMCA.Common.Domain.Auth(including itsRoleMaxLength/PermissionMaxLengthconstants) and EF Core'sModelBuilder. - Concept introduced, the same opt-in-table mapping shape as refresh sessions, applied to a second
framework table.
[Rubric §8, Data Architecture]and[Rubric §11, Security](assesses whether stored authorization data is deliberately keyed and constrained). The class sits besideRefreshSessionModelBuilderExtensionsinPersistence.Authand follows the identical pattern: a callable extension method rather than an inline mapping in a context, so the table only appears in a host's model when something calls it. - Walkthrough
- Two public constants:
TableName = "PermissionGrants"(PermissionGrantModelBuilderExtensions.cs:26) andRolePermissionIndexName = "IX_PermissionGrants_Role_Permission"(:117). - The method null-guards, maps the table with the caller's schema defaulting to
dbo(:126-132), and keys onId(:133). RoleandPermissionare bothIsRequired, length-bounded by the domain's ownRoleMaxLength/PermissionMaxLength, andIsUnicode(false)(:137-145): the comment gives the reason, role and permission names are ASCII identifiers by convention, so a Unicode column would double the index width for nothing.GrantedBygetsHasMaxLength(256)and nothing else (:147), since it is nullable provenance, not a validated identifier.- The unique index over
(Role, Permission)(:153-155) is what makes granting the same permission to the same role twice a no-op rather than a duplicate row: the comment frames a grant as set membership, not a log, so two rows saying the same thing mean nothing extra and would turn "revoke" into a question of how many rows to delete (:149-152). It is also what letsEFPermissionGrantStore's idempotent grant rely on the database rather than a read-then-write race. - The builder is returned for chaining (
:158).
- Two public constants:
- Why it's built this way: ADR-116
layers stored grants over the compiled
IPermissionRegistryas a union-only decorator, and the column shapes here are what make that layer cheap to query: a non-Unicode fixed-shape pair with one unique index answers both "does this role have this permission" reads and idempotent writes without a second lookup. - Where it's used: called by
PermissionGrantModelContributorfromConfigure(PermissionGrantModelBuilderExtensions.cs:94-95) on the one source whose name matchesAuthentication:PermissionGrants:DataSourceName(:90-91); the contributor exists in a host only whenAddStoredPermissionGrantsregisters it, and that registration is the opt-in (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:190-192). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Auth/PermissionGrantModelBuilderExtensionsTests.csand.../Persistence/DbContexts/PermissionGrantModelGateTests.cs, and consumed byEFPermissionGrantStorethrough theDbSet<PermissionGrant>the mapping creates.
ViewAsGrantModelBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/ViewAsGrantModelBuilderExtensions.cs:17· Level 4 · class (public static)
- What it is: the single place the
ViewAsGrantstable is mapped. One extension method,ApplyViewAsGrantConfiguration(this ModelBuilder, string? schema = "dbo"), configures theViewAsGrantentity: table, key, column widths and the two indexes behind the support access history and its retention sweep (ViewAsGrantModelBuilderExtensions.cs:17-63). - Depends on:
ViewAsGrantfromMMCA.Common.Domain.Auth(including itsReasonMaxLengthandDisplayMaxLengthconstants) and EF Core'sModelBuilder. - Concept introduced: none new. The class doc names the refresh-session precedent: applied to the
one context whose source is named by
ViewAs:DataSourceName, only whileViewAs:Enabledis true, so a host that never opts in keeps a byte-identical model (ViewAsGrantModelBuilderExtensions.cs:11-16).[Rubric §8, Data Architecture]and[Rubric §30, Compliance, Privacy and Data Governance](assesses whether a record that names people can be erased and expires). The gateViewAsGrantModelContributorapplies is one condition stricter than the class doc states: it also requiresViewAs:HostsGrantStore(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/ViewAsGrantModelBuilderExtensions.cs:79-82). - Walkthrough
- Three public constants:
TableName = "ViewAsGrants"(ViewAsGrantModelBuilderExtensions.cs:20),TargetIndexName = "IX_ViewAsGrants_TargetUserId_GrantedAt"(:18) andGrantedAtIndexName = "IX_ViewAsGrants_GrantedAt"(:21). - The method null-guards (
:29), maps the table with the caller's schema defaulting todbo(:33) and keys onId(:34),ValueGeneratedNever(:38). The comment at:36-37explains why the key matters most: the primary key IS the per-request lookup (the token'svagclaim), so the guard's check is one seek and reads no other column. ReasonisIsRequiredand bounded byReasonMaxLength(:39);EndedAtis mapped as a plain nullable column (:40).StaffDisplayandTargetDisplayare bounded byDisplayMaxLengthand nullable (:44-45). They are the support access log's display snapshots (emails at grant time), and the comment at:42-43gives both reasons for the nullability: a row written before the snapshot existed has none, and erasure blanks the erased account's.- The
(TargetUserId, GrantedAt)index (:48-49) is the history path, the viewed account's grants newest first (:47); theGrantedAtindex (:52-53) is the retention path, rows issued before a cutoff (:51). - The builder is returned for chaining (
:56).
- Three public constants:
- Why it's built this way: ADR-137 checks the grant on every request a view-as token makes, so the mapping puts that check on the clustered key rather than on a secondary index. Keeping identifying text in nullable snapshot columns rather than in required ones is what lets erasure blank a person out of the log without deleting the access record.
- Where it's used: called by
ViewAsGrantModelContributorfromConfigure(ViewAsGrantModelBuilderExtensions.cs:85-86), whichApplicationDbContextruns fromOnModelCreatingin itsAfterEntityPassespass (ApplicationDbContext.cs:664-666) only whereAppliesToholds:ViewAs:EnabledANDViewAs:HostsGrantStoreAND this instance's physical source name equalsViewAs:DataSourceName(ViewAsGrantModelBuilderExtensions.cs:79-82). Read and written throughEFViewAsGrantStore. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/ViewAs/ViewAsGrantModelGateTests.cs.
PermissionGrantCache
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PermissionGrantCache.cs:35· Level 5 · class (internal sealed)
- What it is: the in-memory snapshot of every role's stored permissions, keyed per role so a
read never scans the whole grant table. It implements
IPermissionGrantCache(the read side) andIPermissionGrantCacheInvalidator(the write-triggered refresh), and both resolve to the same singleton instance (PermissionGrantCache.cs:35-131). - Depends on:
IMemoryCache,IServiceScopeFactory(to resolve the scopedIPermissionGrantStorefor a rebuild),IOptions<PermissionGrantSettings>, and BCLFrozenSet/SemaphoreSlim. - Concept introduced, replace-wholesale rather than mutate-in-place for a cache read from many
threads.
[Rubric §12, Performance & Scalability](assesses whether a hot concurrent read path is lock-free) and[Rubric §11, Security](a reader must never observe a half-built permission set). ASemaphoreSlim(_rebuildLock) serializes rebuilds so the interval refresh and a concurrent administration edit cannot interleave a write from one with the eviction pass of the other (PermissionGrantCache.cs:50, doc at:46-49);_cachedRolesisvolatileand replaced wholesale on every rebuild rather than mutated, so a reader never sees a half-built set (:56, doc at:52-55). - Walkthrough
GetPermissions(role)(PermissionGrantCache.cs:59-62): a plainIMemoryCache.TryGetValuekeyed byCacheKey(role), returningEmpty(a staticFrozenSet<string>,:41) for a blank role or a cache miss. No lock, no allocation on a miss.RefreshAsync(:65-107): takes the rebuild lock, opens a DI scope, resolvesIPermissionGrantStore, reads every grant withGetAllAsync, groups by role (StringComparer.OrdinalIgnoreCase) into per-roleFrozenSet<string>s (StringComparer.Ordinalfor the permission names themselves), writes each role's entry (:89-92), then evicts roles that were cached a moment ago but carry no grant now, in that order, so a role that still has grants is never briefly absent (:96-99, comment at:94-95)._cachedRolesis replaced last (:101).- Entry lifetime is three refresh intervals, not one (
:87,CacheSeconds * 3), for the two reasons the comment gives (:82-86). The next rebuild starts one interval AFTER the previous one finishes, so an entry living exactly one interval would expire before it is rewritten and every cycle would open a window with no stored grants. And when the refresh keeps failing, the snapshot must still stop answering eventually, so a revoke cannot grant forever on a dead database: three intervals is that bound. InvalidateAsync(role, ct)(:110-118): theroleargument narrows what a caller MEANS, not what is reloaded;RefreshAsyncalways reloads everything, and the comment explains why (:112-114): a single query either way, and reloading everything keeps one code path that cannot leave a second role stale because a caller named only the first.Dispose(:126) disposes only the semaphore; the cache entries belong to the host'sIMemoryCacheand are deliberately left alone since this is a singleton whose disposal happens at shutdown (doc at:121-125).CacheKey(role)(:130) upper-cases the role (ToUpperInvariant) before buildingpermgrant:role:{ROLE}. Role names compare case-insensitively everywhere they are read, whileIMemoryCachecompares keys ordinally, so without the normalization a role stored asAdminand read asadminwould miss (comment at:128-129).
- Why it's built this way: one instance answering both the read interface and the invalidator
interface, rather than two collaborating types, is what guarantees an edit and the reads that follow
it cannot end up looking at two different snapshots (the DI registration comment states this
directly,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:196-197). - Where it's used: registered as a singleton for all three roles (concrete type, and the two
interfaces resolved from the same instance) by
AddStoredPermissionGrants(DependencyInjection.Auth.cs:198-202). Refreshed on an interval byPermissionGrantRefreshServiceand read byLayeredPermissionRegistryand the stored-grant administration surface.
RefreshSessionModelBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:23· Level 5 · class (public static)
- What it is: the single place the
RefreshSessionstable is mapped. One extension method,ApplyRefreshSessionConfiguration(this ModelBuilder, string? schema = "dbo"), configures theRefreshSessionentity: table, key, column widths, the three indexes the auth flows read through and the two the retention sweep reads through (RefreshSessionModelBuilderExtensions.cs:23-127). - Depends on:
RefreshSessionfromMMCA.Common.Domain.Auth(including its length constants) and EF Core'sModelBuilder. - Concept introduced, the opt-in framework table.
[Rubric §8, Data Architecture]assesses whether each database holds exactly the data it owns, and[Rubric §11, Security]assesses whether credential storage is designed rather than incidental. The framework owns two kinds of table. The outbox is cross-cutting: every relational source needs one, so it is configured onApplicationDbContextunconditionally and every module's database gets it. Refresh sessions are the other kind: they are Identity-module data, exactly one database owns them, and mapping them everywhere would put an emptyRefreshSessionstable in every other module's migrations. The class doc draws that contrast explicitly and names who calls the method:RefreshSessionModelContributor, only for the context whose source isRefreshSessions:DataSourceNameand only whileRefreshSessions:Enabledis true, or a host's own context class from itsOnModelCreating(RefreshSessionModelBuilderExtensions.cs:13-21). Keeping the mapping in a callable extension method rather than inlining it in a context is what makes "one database, chosen by configuration" expressible at all.PasskeyCredentialModelBuilderExtensionsandViewAsGrantModelBuilderExtensionsrepeat the shape. - Walkthrough
- Six public constants name the objects so tests and callers do not restate strings:
TableName = "RefreshSessions"(RefreshSessionModelBuilderExtensions.cs:26),TokenHashIndexName(:29),UserIndexName(:32),ExpiresAtIndexName = "IX_RefreshSessions_ExpiresAt"(:35),RevokedAtIndexName = "IX_RefreshSessions_RevokedAt"(:38) andSignInIndexName = "IX_RefreshSessions_UserId_SignInId"(:41). - The method null-guards (
RefreshSessionModelBuilderExtensions.cs:52), maps the table with the caller's schema defaulting todbo(:50,:56), and keys onId(:57). TokenHashisIsRequired,HasMaxLength(RefreshSession.TokenHashLength),IsUnicode(false),IsFixedLength()(RefreshSessionModelBuilderExtensions.cs:61-65). The constant is 64 (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:49), the length of a SHA-256 digest rendered as hex. The comment at:59-60gives the reason for the three facets: the value is always a 64-character hex digest, so a Unicode or variable-width column would double the index it has to fit in for nothing.ReplacedByTokenHashgets the same three facets minusIsRequired(RefreshSessionModelBuilderExtensions.cs:67-70), because it is null until the session is rotated.ReasonRevoked,IpAddressandUserAgenttake their lengths from the domain constants (64, 45 and 512 atRefreshSession.cs:58,:52,:55), the first two non-Unicode (RefreshSessionModelBuilderExtensions.cs:72-74). 45 is the length of a full IPv6 text form;UserAgentstays Unicode because a user-agent string is arbitrary client text.- Seven device columns, the metadata a native client reports for its session, all bounded by
RefreshSession.DeviceFieldMaxLength(256,RefreshSession.cs:64) (RefreshSessionModelBuilderExtensions.cs:79-85). The machine identifiers (DeviceId,DevicePlatform,DeviceFormFactor,DeviceType) are non-Unicode;DeviceName,DeviceModelandDeviceManufacturerare free text, so Unicode (comment at:76-78). - The unique index over
TokenHash(RefreshSessionModelBuilderExtensions.cs:91-93) is the validation path: every refresh presents a token and must be answered by exactly one row. The comment at:87-90gives two reasons for the uniqueness, and both are security reasons rather than performance ones: a hash collision across users would let one account's token validate against another's session, and a double-insert of the same token becomes a database error instead of an ambiguity the reuse check has to resolve. - The composite index on
(UserId, RevokedAt)(RefreshSessionModelBuilderExtensions.cs:97-98) serves the family question, "every live session for this user", which is asked on the per-user session cap, on reuse detection and on sign-out-everywhere. Without it each of those scans the table (:95-96). SignInIdis mapped as a plain nullableGuid(RefreshSessionModelBuilderExtensions.cs:107) and the(UserId, SignInId, CreatedAt)index namedSignInIndexName(:108-109) serves the sign-in history. The comment at:100-106explains the column order:CreatedAttrails so the history's MIN and MAX per sign-in and the lookup of each sign-in's newest row are answered from the index alone, never by visiting every row of a long rotation chain. TheGuidis left to each engine's own mapping and the index declares no filter or INCLUDE list, so one configuration serves every relational engine; rows written before the column existed hold null.- Two single-column indexes serve the retention path of
RefreshSessionCleanupService:ExpiresAtnamedExpiresAtIndexName(RefreshSessionModelBuilderExtensions.cs:118-119) andRevokedAtnamedRevokedAtIndexName(:121-122). The comment at:111-117gives the reason: a row is past retention when it was revoked before the cutoff, or never revoked and expired before it, and neither index above leads with either column, so without these the six-hourly sweep would re-scan the whole table for every batch on every replica (the outbox and audit-trail sweeps have their own retention index for the same reason). One plain index per leg, with no filter or INCLUDE list, keeps one configuration valid on every relational engine and lets eachORbranch of the sweep's predicate seek its own index. - The builder is returned for chaining (
RefreshSessionModelBuilderExtensions.cs:125).
- Six public constants name the objects so tests and callers do not restate strings:
- Why it's built this way: hashing the token rather than storing it, and rotating per device, is ADR-097, which supersedes the single-plaintext-column storage model of ADR-050 while keeping its rotation and reuse-detection policy. The column shapes here are what make that model cheap: a fixed-width non-Unicode digest keeps the unique index narrow, and the three indexes are exactly the three questions
EFRefreshSessionStoreasks (this token, this user's live family, this user's sign-ins), and the two retention indexes are the two legs of the one question the sweep asks (which rows died before the cutoff). Nothing here is soft-deletable and nothing is audit-stamped, which is deliberate and is why the table needs its own mapping method rather than riding the module entity-configuration mechanism. - Where it's used: called by
RefreshSessionModelContributorfromConfigure(RefreshSessionModelBuilderExtensions.cs:151-152), whichApplicationDbContextruns fromOnModelCreatingin itsAfterEntityPassespass (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:664-666) behind the contributor's two-partAppliesTo:RefreshSessions:Enabledis true and this context's physical source name equalsRefreshSessions:DataSourceName(RefreshSessionModelBuilderExtensions.cs:146-148). At design time the same gate is fed byDesignTimeDbContextOptions.EnableRefreshSessions. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Auth/RefreshSessionModelBuilderExtensionsTests.csand, for the gate itself,.../Persistence/DbContexts/RefreshSessionModelGateTests.cs. - Caveats / not-in-source: the class doc is current, but the method's own summary still says "Call it from the Identity database's context (after
base.OnModelCreating(modelBuilder))" (RefreshSessionModelBuilderExtensions.cs:43-46), which describes the hand-called arrangement only. The framework calls it throughRefreshSessionModelContributorbehind the gate, and the contributor's doc explains why (RefreshSessionModelBuilderExtensions.cs:129-138): ADR-006 leaves consumers no context class to override (ADR-006), and the session entity is not anAuditableBaseEntity, so the module entity-configuration mechanism never reaches it. Calling it by hand remains supported for a host that does have its own context class.
PasskeyCredentialModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PasskeyCredentialModelBuilderExtensions.cs:72· Level 9 · class (internal sealed)
- What it is: the
IModelContributorthat puts thePasskeyCredentialstable into a context's model. It decides which physical source gets the table and then callsPasskeyCredentialModelBuilderExtensions.ApplyPasskeyCredentialConfiguration(PasskeyCredentialModelBuilderExtensions.cs:72-85). It is the first of four structurally identical auth-table contributors in this part; the other three cross-reference this section. - Depends on:
IModelContributor,ModelContributorPhase,PhysicalDataSource,DataSourceandIOptions<PasskeySettings>as its one primary-constructor parameter (PasskeyCredentialModelBuilderExtensions.cs:72). - Concept introduced, an optional table as a registered contributor rather than a context flag.
[Rubric §8, Data Architecture]assesses whether each database holds exactly the data it owns; a contributor answers "does this source get the table" once, inAppliesTo, and nothing else in the context has to know the table exists.ApplicationDbContextresolves every registered contributor inOnConfiguring, keeps only those whoseAppliesToaccepts this context's physical source, relational engines only, ordered byPhase(stable, so a phase keeps registration order) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:547-554).OnModelCreatingruns them in two passes,BeforeEntityPassesandAfterEntityPasses(ApplicationDbContext.cs:649,:448). Because the applying set changes the model, its type names join the model cache key asModelContributorKey(ApplicationDbContext.cs:114-115, doc at:92-106), so two contexts on one source with different contributor sets never share a cached model. The general contract and the other framework contributors are taught atIModelContributor. - Walkthrough
PhaseanswersAfterEntityPasses(PasskeyCredentialModelBuilderExtensions.cs:75): the passkey row is framework bookkeeping, not an auditable entity, so it is mapped after the soft-delete filter, tenant filter and concurrency passes and none of them touches it (ApplicationDbContext.cs:664-666).AppliesTo(:78-80) holds only whilePasskeys:Enabledis true AND the source'sKey.NameequalsPasskeys:DataSourceNameunder ordinal comparison.Configure(:83-84) ignores the engine and callsApplyPasskeyCredentialConfiguration()with its defaultdboschema.
- Why it's built this way: ADR-148
moves every optional framework table onto this one extension point, so a host that opts into
nothing builds exactly the base model and its migrations never see the table. ADR-139
makes passkeys opt-in, hence the
Enabledleg. The contributor is registered in Infrastructure rather than inAddPasskeysbecause the opt-in passkeys package references the application layer only; with noAddPasskeyscall the settings read as their disabled defaults, so no model changes (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:231-233). - Where it's used: registered with
TryAddEnumerableas a singletonIModelContributoron every host (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:234-235); added at design time whenDesignTimeDbContextOptions.EnablePasskeysis set (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:204). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/Passkeys/PasskeyModelGateTests.cs,.../DependencyInjectionModelContributorTests.csand.../Persistence/DataSources/ModelCacheKeyGateTests.cs.
PermissionGrantModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PermissionGrantModelBuilderExtensions.cs:84· Level 9 · class (internal sealed)
- What it is: the
IModelContributorfor thePermissionGrantstable; it callsPermissionGrantModelBuilderExtensions.ApplyPermissionGrantConfigurationon the one source the settings name (PermissionGrantModelBuilderExtensions.cs:84-96). - Depends on:
IOptions<PermissionGrantSettings>as its primary-constructor parameter (:84), plus the contributor types listed atPasskeyCredentialModelContributor. - Concept introduced: none new; the shape is
PasskeyCredentialModelContributor's.[Rubric §11, Security](assesses whether stored authorization data is an explicit choice) applies through the one difference below. - Walkthrough:
PhaseisAfterEntityPasses(:87).AppliesTo(:90-91) checks only that the source'sKey.Nameequals the configuredDataSourceName, ordinally: there is noEnabledleg, because the registration itself is the opt-in.Configure(:94-95) callsApplyPermissionGrantConfiguration(). - Why it's built this way: unlike the other three auth contributors, this one is not registered on
every host. Only
AddStoredPermissionGrantsregisters it, and the comment there says so: "its registration IS the opt-in" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:190-192). A host that never calls it never sees the table, so a settings flag would be redundant. ADR-116 makes stored grants opt-in; ADR-148 is the extension point. - Where it's used: registered with
TryAddEnumerablebyAddStoredPermissionGrants(DependencyInjection.Auth.cs:191-192); added at design time behindDesignTimeDbContextOptions.EnableStoredPermissionGrants(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:198). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/PermissionGrantModelGateTests.cs,.../DependencyInjectionStoredPermissionGrantsTests.cs,.../DependencyInjectionModelContributorTests.csand.../Persistence/DataSources/ModelCacheKeyGateTests.cs.
RefreshSessionModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:140· Level 9 · class (internal sealed)
- What it is: the
IModelContributorfor theRefreshSessionstable; it callsRefreshSessionModelBuilderExtensions.ApplyRefreshSessionConfiguration(RefreshSessionModelBuilderExtensions.cs:140-153). - Depends on:
IOptions<RefreshSessionSettings>as its primary-constructor parameter (:121), plus the contributor types listed atPasskeyCredentialModelContributor. - Concept introduced: none new; the shape is
PasskeyCredentialModelContributor's. - Walkthrough:
PhaseisAfterEntityPasses(:124).AppliesTo(:127-129) holds whileRefreshSessions:Enabledis true AND the source'sKey.NameequalsRefreshSessions:DataSourceName, ordinally.Configure(:132-133) callsApplyRefreshSessionConfiguration(). - Why it's built this way: refresh sessions are Identity-module data owned by exactly one database
(ADR-097), so the
contributor is registered everywhere but inert until enabled, and then only on the named source
(registration comment at
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:193-195). ADR-148 is the extension point. - Where it's used: registered with
TryAddEnumerablebeside theRefreshSessionSettingsbinding (DependencyInjection.cs:196-197); added at design time behindDesignTimeDbContextOptions.EnableRefreshSessions(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:196). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/RefreshSessionModelGateTests.cs,.../DependencyInjectionModelContributorTests.csand.../Persistence/DataSources/ModelCacheKeyGateTests.cs.
ViewAsGrantModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/ViewAsGrantModelBuilderExtensions.cs:73· Level 9 · class (internal sealed)
- What it is: the
IModelContributorfor theViewAsGrantstable; it callsViewAsGrantModelBuilderExtensions.ApplyViewAsGrantConfiguration(ViewAsGrantModelBuilderExtensions.cs:73-87). - Depends on:
IOptions<ViewAsSettings>as its primary-constructor parameter (:73), plus the contributor types listed atPasskeyCredentialModelContributor. - Concept introduced: none new; the shape is
PasskeyCredentialModelContributor's. - Walkthrough:
PhaseisAfterEntityPasses(:76).AppliesTo(:79-82) is the one three-legged gate of the four:ViewAs:EnabledANDViewAs:HostsGrantStoreAND the source'sKey.NameequalsViewAs:DataSourceName, ordinally.Configure(:85-86) callsApplyViewAsGrantConfiguration(). - Why it's built this way:
HostsGrantStorelets a multi-service host enable view-as on every service while only the Identity service carries the table (registration comment atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:212-216). The same two settings areEFViewAsGrantStore'sEnabledcheck, which is what keeps the store from ever querying a table this contributor declined to map. ADR-137 makes view-as opt-in; ADR-148 is the extension point. - Where it's used: registered with
TryAddEnumerableon every host (DependencyInjection.cs:223-224); added at design time behindDesignTimeDbContextOptions.EnableViewAsGrants(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:200). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/ViewAs/ViewAsGrantModelGateTests.cs,.../Auth/ViewAs/ViewAsGrantSnapshotModelTests.cs,.../DependencyInjectionModelContributorTests.csand.../Persistence/DataSources/ModelCacheKeyGateTests.cs.
EFPasskeyCredentialStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFPasskeyCredentialStore.cs:28· Level 13 · class (internal sealed)
- What it is: the EF Core implementation of
IPasskeyCredentialStore, the persistence side of passkey sign-in. It lists, finds, adds, updates and removesPasskeyCredentialrows in the database that maps thePasskeyCredentialstable (EFPasskeyCredentialStore.cs:28-86). - Depends on:
IDbContextFactory(context access and saving),IEntityDataSourceRegistryandIDataSourceResolver(source resolution) andIOptions<PasskeySettings>, all primary-constructor parameters (EFPasskeyCredentialStore.cs:28-32). - Concept introduced, registered everywhere and inert by its callers.
[Rubric §8, Data Architecture]and[Rubric §11, Security]. The class doc states the arrangement (EFPasskeyCredentialStore.cs:18-21):AddInfrastructureregisters the store on every host, but only the opt-inAddPasskeysregisters the ceremony service that reads it, and every caller sits behindPasskeys:Enabled, so it never queries a table the model does not carry. The store itself carries no enabled check. ContrastEFViewAsGrantStore, whose callers are bound on every host and which therefore guards each member itself. - Walkthrough
Context(EFPasskeyCredentialStore.cs:34) resolves the context per access through the factory keyed onResolveDataSourceKey();Credentials(:36) is theDbSet<PasskeyCredential>over it.ListForUserAsync(:39-45) is anAsNoTrackingread of one account's passkeys ordered byCreatedOn, backed by theUserIdindex.FindAsync(userId, id)(:48-49) filters on bothIdandUserId, so a client-supplied id cannot reach another account's passkey.FindByCredentialIdAsync(:52-53) is the sign-in lookup on the uniqueCredentialIdindex. Both are tracked.AddAsync(:56-62) adds and saves at once, unlikeEFRefreshSessionStore's staged insert.UpdateAsync(:65-72) only saves: the row came fromFindAsyncorFindByCredentialIdAsync, which track it, so the change is already known to the context (comment at:69-70). That is why those two reads are tracked; a caller that passed an untracked instance would save nothing.RemoveAsync(:75-81) removes the tracked row and saves, a hard delete.ResolveDataSourceKey(:84-85) delegates toFrameworkTableTargets.ResolveHome<PasskeyCredential>with the configuredPasskeys:DataSourceName(comment at:83): the entity registry first, otherwise the resolver's engine forDefaultplus that name, used verbatim (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:105-113). It is the one resolution every store and sweep over an opt-in framework table shares, so a sweep can never visit a different database than its store reads (FrameworkTableTargets.cs:84-92).
- Why it's built this way: ADR-139
keeps passkeys opt-in, so the registration costs nothing until a host calls
AddPasskeys. A passkey row is framework bookkeeping, not an aggregate, so removing one deletes it outright rather than soft-deleting it (ADR-005, ADR-119); the shared soft-delete fitness base names this type for that reason (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Domain/SoftDeleteEnforcementTestsBase.cs:61). - Where it's used: registered as the scoped
IPasskeyCredentialStoreon every host (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:229, comment at:214-216). The consumer isPasskeyService(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyService.cs:36). Also named byMMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/DataSourceBranchingFitnessTests.cs.
EFPermissionGrantStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFPermissionGrantStore.cs:35· Level 13 · class (internal sealed)
- What it is: the EF Core implementation of
IPermissionGrantStore, the persistence side of stored permission grants (EFPermissionGrantStore.cs:35-207). It lists, grants and revokes rows in thePermissionGrantstable. - Depends on:
IDbContextFactory(context access and saving),IEntityDataSourceRegistryandIDataSourceResolver(source resolution),IOptions<PermissionGrantSettings>,TimeProvider, andIUniqueConstraintViolationDetector(classifies the unique-index failure a concurrent duplicate grant raises), all primary-constructor parameters (EFPermissionGrantStore.cs:35-41). - Concept introduced, check-then-act made harmless by a unique index, rather than a database-level
conditional update.
[Rubric §11, Security](assesses whether a duplicate grant is handled deliberately) and[Rubric §8, Data Architecture]. UnlikeEFRefreshSessionStore's rotation claim, granting a permission is idempotent by nature (a role either has a permission or it does not), soGrantAsyncuses an ordinary check-then-act: query for an existing row, and only insert when none is found (EFPermissionGrantStore.cs:98-123). The role it checks and writes is first folded to the spelling already stored (seeCanonicalRoleAsyncbelow). The comment names why that race is harmless here (:98-101): the unique index on(Role, Permission)makes a concurrent duplicate insert fail at the database, the loser catches that failure and answers success, because the row the winner wrote says exactly what the loser was trying to say. The check exists to make the ordinary duplicate free, not to be the guarantee. - Walkthrough
Context(EFPermissionGrantStore.cs:43) resolves the context per access through the factory, keyed onResolveDataSourceKey();Grants(:45) is theDbSet<PermissionGrant>over it.GetAllAsync(:48-54) andGetPermissionsAsync(role, ct)(:57-73) are bothAsNoTrackingreads, the first ordered byRolethenPermissionfor the administration listing, the second filtered to every stored spelling of one role (storedRoles.Contains(g.Role),:67), projected to bare permission strings,Distinct()and ordered (:68-70), forPermissionGrantCache's rebuild.GrantAsync(role, permission, grantedBy, ct)(:76-126) first resolves a valid role to the spelling already stored throughCanonicalRoleAsync(:83-85; an invalid role is left forCreateto refuse), constructs aPermissionGrantthrough itsCreatefactory, and unwraps the result withTryGetValue(out var grant), returning the factory's failure untouched on invalid input (:93-96), then runs the check-then-act described above: an existing row returns success without writing anything (:102-110), otherwise the grant is added to the resolved context and saved (:112-117). ADbUpdateExceptionthat the detector classifies as a unique-constraint violation is caught (:118): the insert lost the race to a concurrent duplicate, so its entry is set toEntityState.Detached(:122, comment at:120-121) so the scoped context does not retry the failed insert on its next save, and the method still returns success. Any other database failure propagates.RevokeAsync(role, permission, ct)(:129-149) is a set-basedExecuteDeleteAsyncfiltered on every stored spelling of the role and the permission (:143-146), never a load-then-remove: there is at most one row per stored spelling by the unique index, nothing about them needs to be read, and removing zero rows is exactly the success an idempotent revoke promises (comment at:139-142). Every spelling goes, so a pre-existing duplicate casing cannot keep the grant alive.CanonicalRoleAsyncandStoredSpellingsAsync(:166-170,:185-202) fold role casing. TheRoleis compared case-insensitively everywhere it is read, but an equality predicate is only as case-insensitive as the column collation (case-sensitive on PostgreSQL and SQLite), and folding inside the predicate would defeat the unique index (remarks:155-162). So the fold happens in memory over the distinct stored role names:StoredSpellingsAsyncreturns every stored spelling matching the trimmed role underOrdinalIgnoreCase, ordinally sorted, or just the trimmed role when none is stored (:196-201);CanonicalRoleAsynctakes the first, which is the spelling a grant writes. Reads and revokes use all of them (Role IN (...), remarks:176-181), so a table that already holds two casings of one role (written before that rule) is not kept apart.ResolveDataSourceKey(:205-206, comment at:204) delegates toFrameworkTableTargets.ResolveHome<PermissionGrant>, the resolutionEFRefreshSessionStoreand the other opt-in framework stores share: the entity registry first (so a consumer entity configuration forPermissionGrantroutes it like any other entity), otherwise a key built from the resolver's engine forDefaultplus the configuredDataSourceName. Only the engine goes through the resolver; the configured name is used verbatim, so a host that configures no SQL Server connection string gets the engine it does configure rather than a context over an empty connection string (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:94-96).
- Why it's built this way: the store is intentionally the thinnest possible layer over the model
PermissionGrantModelBuilderExtensionsmaps: every method is a direct translation of oneIPermissionGrantStoreoperation into one query or one set-based statement, with no caching or batching of its own, becausePermissionGrantCacheis the layer that owns performance and this one owns correctness against the database. - Where it's used: registered as the scoped
IPermissionGrantStorebyAddStoredPermissionGrants(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:194). Listed as a sanctioned soft-delete exception alongside the other framework bookkeeping stores in bothMMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Domain/SoftDeleteEnforcementTests.csandMMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Domain/SoftDeleteEnforcementTests.cs, sincePermissionGrantis deleted withExecuteDeleteAsyncrather than soft-deleted, the same reasoning ADR-119 applies to framework bookkeeping rows generally.
EFRefreshSessionStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:34· Level 13 · class (internal sealed)
- What it is: the EF Core implementation of
IRefreshSessionStore, the persistence side of multi-device refresh tokens. It reads and writesRefreshSessionrows in whichever physical database holds them, and it owns the one operation the auth flow cannot express as a plain tracked mutation: the rotation claim (EFRefreshSessionStore.cs:34-393). - Depends on:
IDbContextFactory(context access, saving and transactions),IEntityDataSourceRegistryandIDataSourceResolver(source resolution),RefreshSessionSettingsviaIOptions<T>,RefreshSession,RefreshSessionSignIn, the nestedSignInChainRow, and theUserIdentifierTypealias. All four dependencies are primary-constructor parameters (EFRefreshSessionStore.cs:34-38). - Concept introduced, letting the database arbitrate a race instead of the process.
[Rubric §11, Security]assesses whether credential handling is correct under concurrency, and[Rubric §12, Performance and Scalability]assesses whether the concurrency strategy holds with more than one instance running. Refresh-token rotation is a check-then-act: read the presented session, confirm it is live, revoke it, insert the successor. Two concurrent refreshes of the same token each read their own copy withRevokedAtnull, and both would happily save, which is two valid successors from one token. The row deliberately carries no concurrency token, so the fix is to make the revocation itself the arbitration: a conditionalUPDATE ... WHERE Id = @id AND RevokedAt IS NULL. Exactly one caller affects one row and wins; the loser affects zero rows and writes nothing. The remarks state this in full (EFRefreshSessionStore.cs:317-322; the successor and claim share one transaction,:325-329). - Walkthrough
Context(EFRefreshSessionStore.cs:40) resolves the context per access through the factory keyed onResolveDataSourceKey(), andSessions(:42) is theDbSet<RefreshSession>over it.ResolveDataSourceKey(EFRefreshSessionStore.cs:378-379, comment at:377) is the routing decision, and it delegates toFrameworkTableTargets.ResolveHome<RefreshSession>, the one resolution every store and sweep over an opt-in framework table shares (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:84-92). It has two legs. First the entity registry, so a consumer that ships a real entity configuration forRefreshSessionroutes it like any other entity. Otherwise a key built from the resolver's engine forDefaultplus the configuredDataSourceName(FrameworkTableTargets.cs:109-113). The remarks there are precise about the split (FrameworkTableTargets.cs:94-96): the configured NAME is used verbatim, and only the ENGINE goes through the resolver, so a host that configures no SQL Server connection string gets the engine it does configure rather than a context over an empty connection string.AddAsync(EFRefreshSessionStore.cs:45-49) stages the insert; it does not save.SaveChangesAsync(:311-312) delegates to the factory, which is what lets a login and its session insert commit in the same unit of work.FindByTokenHashAsync(EFRefreshSessionStore.cs:52-58) is the validation lookup, backed by the uniqueTokenHashindex. It and the other single-row reads return theFirstOrDefaultAsynctask directly, since there is nothing to do after an await.GetUnrevokedByUserAsync(EFRefreshSessionStore.cs:65-73) is the family query, ordered byCreatedAtthenId. The tie-break is not cosmetic: the per-user cap evicts "the oldest", and two sessions opened in the same clock tick would otherwise evict in an arbitrary order (:61-64).GetAllByUserAsync(EFRefreshSessionStore.cs:77-85) returns every session of a user, revoked or not, in the sameCreatedAtthenIdorder, and is tracked: erasure revokes and anonymizes the returned rows in place (:76).GetRecentSignInsAsync(EFRefreshSessionStore.cs:96-147) is the sign-in history: the newestmaxSignInssign-ins of one user, each with the session that currently represents it. The remarks (:88-95) set the budget: at most three statements, each bounded bymaxSignInsand none by the user's row count, all untracked because a history read never revokes (AsNoTracking,:103). It rejects a non-positive count (:101), then:- runs
SignInChainsQuery(:158-173), which groups the user's rows bySignInIdin the database and returns oneSignInChainRowper sign-in (MIN and MAX ofCreatedAt), newest first, limited (:105-107); - when any chain came back (
:110), runsSignInHeadsQuery(:186-193), which loads the rows whoseSignInIdis in the chain list and whoseCreatedAtis in the list of newest instants (:112-118). TwoINlists can pair one chain's id with another chain's instant, and two rows of a chain can share its newest instant, so the head is matched exactly in memory withIdas the tie-break, one head per sign-in (:125-127, comment at:122-124); - runs
LegacySignInsQuery(:204-214) for rows written beforeSignInIdexisted:SignInIdnull and not revoked as rotated, newest first, limited (:135-137). Each such row counts as its own sign-in, keyed by its ownId, because a rotated legacy row is represented by its successor; - merges both lists, orders by start then id descending and takes
maxSignIns(:139-146). The(UserId, SignInId, CreatedAt)index fromRefreshSessionModelBuilderExtensionscovers the first two statements, and the legacy predicate leads with the same(UserId, SignInId IS NULL)prefix (:198).
- runs
LiveSessionUserIds(now)(EFRefreshSessionStore.cs:254-257) is the shared live predicate,RevokedAt == null && ExpiresAt > nowprojected toUserId:RefreshSession.IsActiveAtspelled out so it translates to SQL (comment at:253). Two members build on it.GetUserIdsWithLiveSessionsAsync(now, limit)(EFRefreshSessionStore.cs:222-235) is a bounded scalar projection: it rejects a non-positivelimit(:227), then takes the distinct ids, orders them and cuts atlimit, so a bounded read is deterministic (remarks:217-221). It tracks nothing, because no caller revokes through these rows.QueryUserIdsWithLiveSessions(userEntityType, now)(EFRefreshSessionStore.cs:243-251) returns the same predicate as an unexecutedIQueryablefor a caller to compose, but only when the registry routes the user entity to the same source as the sessions; otherwise it answersnull. An entity the registry does not know is treated as living elsewhere, so the caller takes the bounded fallback rather than a query EF would refuse to run across two context instances (remarks:238-242).UserSessionsAdministrationServicetries the composed query first and falls back to the bounded list (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:95,:105).CountLiveSessionsByUserAsync(EFRefreshSessionStore.cs:264-283) answers live-session counts per user in one grouped query over aContainsof the distinct requested ids, so a duplicate id cannot double a count; an empty request returns an empty dictionary without touching the database (:272-275, remarks:260-263).FindByIdAsync(EFRefreshSessionStore.cs:291-296) filters on bothIdandUserId. The remarks make the security argument (:286-290): the id arrives from a client, so putting the user in the predicate is what makes another account's session unreadable rather than merely rejected after being read.FindByIdUntrackedAsync(EFRefreshSessionStore.cs:305-308) is a no-tracking entity read viaAsNoTracking(), filtering onIdalone. It exists to see past the tracked copy (which the identity map would otherwise hand back unchanged) to the row the database holds after a concurrent rotation, so a rotation loser can re-read the winner's result. Nothing revokes through the instance it returns (remarks at:299-304). The caller isAuthSessionIssuer(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:569).TryRotateAsync(EFRefreshSessionStore.cs:332-375) is the claim. The tracked entry for the presented session is captured before the transaction opens so this context is one of the contexts the factory enlists rather than a late arrival (:343, comment at:341-342). InsideExecuteInTransactionAsync(:345) it issues the conditionalExecuteUpdateAsyncsettingRevokedAt,ReasonRevoked = RefreshSession.ReasonRotatedandReplacedByTokenHash, and treats "one row affected" as the claim (:348-356). Losing returnsfalseand writes nothing (:358-361).- Having won, it mirrors the claim onto the tracked instance with
presented.Revoke(...)and then copies current values over original values (EFRefreshSessionStore.cs:366-367). That second line is easy to miss and load-bearing: without it, the nextSaveChangeswould re-issue the sameUPDATEas a tracked modification (:363-365). Then the successor is added and saved inside the same transaction (:369-370). - Sharing one transaction between the claim and the successor insert is what stops a loser observing a half-finished rotation: its
UPDATEblocks on the winner's row lock, re-evaluates the predicate after the winner commits, and the family revocation it then performs sees the committed successor. A nested call joins the ambient transaction, so anITransactionalcaller is unaffected (EFRefreshSessionStore.cs:325-329).
- Why it's built this way: every read that returns
RefreshSessionentities for a caller to act on is tracked on purpose, and the class doc says why (EFRefreshSessionStore.cs:25-31): the caller revokes by mutating the instances this returns, so a no-tracking query would take those revocations and silently drop them at save time. That is the opposite of the usual read-path default in this codebase and worth remembering. The class doc names the two entity exceptions,FindByIdUntrackedAsync(a read-only re-read for the rotation loser) andGetRecentSignInsAsync(a read-only history page) (:27-29); the two scalar projections return no entities, so nothing is tracked there either (:29-31). Resolving the database through the registry first and the setting second means a single-database host needs no configuration at all (RefreshSessions:DataSourceNamedefaults toDefaultatMMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:52) while a multi-database host names the Identity source once. Pointing it at a database that does not map the table fails loudly on the first query rather than reading the wrong rows (EFRefreshSessionStore.cs:21-22). The policy is ADR-097, building on ADR-050; the claim's transaction follows ADR-107. - Where it's used: registered as the scoped
IRefreshSessionStore(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:191), scoped deliberately, like the unit of work it shares aDbContextwith, so a login and its session insert commit together (:185-186).AuthSessionIssuerdrives issue and rotation through it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:56),SignInHistoryreads the sign-in history (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:45), andUserSessionsAdministrationServiceserves the session administration surface (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:20).DeleteUserHandlerBase<TUser, TCommand>revokes and anonymizes a deleted user's sessions throughRefreshSessionRevocationover the same store (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:176-177).RefreshSessionCleanupServiceroutes through the sameFrameworkTableTargets.ResolveHome<RefreshSession>call, so the two can never disagree on the database.
EFViewAsGrantStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFViewAsGrantStore.cs:32· Level 13 · class (internal sealed)
- What it is: the EF Core implementation of
IViewAsGrantStore, the persistence side of read-only view-as support access. It writes, finds, ends, lists, purges and erasesViewAsGrantrows (EFViewAsGrantStore.cs:32-175). - Depends on:
IDbContextFactory,IEntityDataSourceRegistry,IDataSourceResolverandIOptions<ViewAsSettings>as primary-constructor parameters (EFViewAsGrantStore.cs:32-36), plusViewAsGrantLogQuery,PagingMathandViewAsGrantListRequestfor the paged log. - Concept introduced, a store that answers "nothing" while its table is unmapped.
[Rubric §8, Data Architecture]and[Rubric §11, Security](assesses whether a disabled feature degrades to a safe answer rather than a fault). The store is registered and its callers bound on every host, but the table exists only whereViewAs:EnabledandViewAs:HostsGrantStoreboth hold.Enabled(EFViewAsGrantStore.cs:39) is those same two settings, the model gate's pair (doc at:38), and every member checks it first: reads answernull, empty or0,EndAsyncanswersfalse, and the one write,AddAsync, throws throughRequireEnabled(:164-170) naming both settings. The class doc gives the payoff (:20-25): the sign-in history can read through this store and the controller actions can bind the view-as service on every host without ever querying a table that is not there. - Walkthrough
Context(EFViewAsGrantStore.cs:41) andGrants(:43) are the per-access context andDbSet<ViewAsGrant>, routed byResolveDataSourceKey.AddAsync(:46-53) requires the feature, adds and saves at once.FindAsync(:56-59) is anAsNoTrackingprimary-key read, the per-request grant check.EndAsync(:62-84) loads the grant tracked byIdandStaffUserId, so only the staff member who holds a grant can end it; it ends and saves only a grant not already ended (:77-81), and answerstruefor an already-ended one, which makes ending idempotent.GetRecentForTargetAsync(:87-104) returns the viewed account's newest grants, up tomaxCount, untracked; a non-positive count answers empty.DeleteIssuedBeforeAsync(:107-110) is the retention purge, one set-basedExecuteDeleteAsyncoverGrantedAt < cutoff, the predicate theGrantedAtindex serves.ListAsync(:120-144) is the support access log: filters throughViewAsGrantLogQuery.Filter(:131), clamps paging withPagingMath.ClampagainstViewAsGrantListRequest.MaxPageSizeinto onewindow(:132), then counts and pages withwindow.Skipandwindow.Take(:138-139), ordered byGrantedAtdescending withIdas tie-break. The remarks (:113-119) give the two reasons: the tie-break stops equal instants repeating or skipping a row across pages, and the email needles are folded byViewAsGrant.NormalizeDisplay, the form the snapshots are stored in, so the match does not depend on database collation.ForgetUserAsync(:147-162) loads, tracked, every grant where the user is the staff side with a staff display or the target side with a target display, blanks that user's snapshot withForgetDisplayOfand returns how many rows changed (:161). It does not save: the comment at:154-155says the erasure's own unit-of-work save persists the blanking, so it commits or rolls back with the rest of the erasure.ResolveDataSourceKey(:173-174, comment at:172) delegates toFrameworkTableTargets.ResolveHome<ViewAsGrant>, the resolution it shares withEFPermissionGrantStoreand the other opt-in framework stores: the registry first, then the resolver's engine plusViewAs:DataSourceNameused verbatim (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:105-113).
- Why it's built this way: ADR-137
makes view-as opt-in and read-only, so the store has to be harmless on a host that never enabled it.
Retention deletes rows outright because a grant is framework bookkeeping, not an aggregate
(ADR-119), while erasure
blanks the person's snapshot and keeps the access record
(ADR-005). The shared
soft-delete fitness base names this type
(
MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Domain/SoftDeleteEnforcementTestsBase.cs:55). - Where it's used: registered as the scoped
IViewAsGrantStoreon every host (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:221, comment at:200-204). Consumed byViewAsService(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:43) and byViewAsGrantsAdminControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:61). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/ViewAs/EFViewAsGrantStoreTests.cs.
RefreshSessionCleanupService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Auth·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionCleanupService.cs:53· Level 13 · class (public sealed partial,PeriodicBackgroundService)
- What it is: the retention sweep for the
RefreshSessionstable. On an interval it hard-deletes every session that stopped being usable more thanRetentionDaysago (RefreshSessionCleanupService.cs:53-172). - Depends on:
IServiceScopeFactory,ILogger<RefreshSessionCleanupService>,IOptions<RefreshSessionSettings>,TimeProviderand an optionalIDistributedLockcycleLock(defaultnull), all primary-constructor parameters, the clock and logger passed straight to thePeriodicBackgroundServicebase (RefreshSessionCleanupService.cs:53-59); inside a sweep it resolvesIEntityDataSourceRegistry,IDataSourceResolverandIDbContextFactoryfrom the scope (:122-125), routes throughFrameworkTableTargets, and deletes throughBatchedDelete. - Concept introduced, hard delete inside a soft-delete framework.
[Rubric §30, Compliance, Privacy and Data Governance]assesses whether personal data has a bounded lifetime, and[Rubric §8, Data Architecture]assesses whether operational tables have a retention story. Everything modelled as an aggregate here is soft-deleted (ADR-005), so a hardDELETEis conspicuous and the class doc justifies it (RefreshSessionCleanupService.cs:19-23): a session is framework bookkeeping, not an aggregate. The row has no soft-delete flag and no audit stamps, and its content is a credential digest plus the IP, user-agent and device metadata of the device that signed in. Keeping it past its usefulness is a growing table and a growing set of records describing a data subject's devices, so the sweep removes the row rather than flagging it. - Walkthrough
_settingsis captured once;_timeProviderre-captures the same constructor parameter into a field rather than reusing it directly, because the base constructor already consumes it and doing so would beCS9107(RefreshSessionCleanupService.cs:61-65).- The loop mechanics, the wait-then-sweep cycle and the catch-log-continue behavior live once in
PeriodicBackgroundService; this type supplies six overrides.CycleLockreturns the injectedcycleLock(:72): the purge is idempotent, so when the host registers a lock (AddInfrastructurealways does) it runs on one replica per interval rather than once per replica, and anulllock sweeps on every replica (remarks:68-71, parameter doc:49-52).IntervalreturnsCleanupIntervalHoursas hours (:75).StartupDelayreturnsIntervalitself (:81, doc:77-80), so the first sweep waits one full interval, unlikePermissionGrantRefreshService, which primes immediately.IsEnabled(:84-104) replaces the two early-exit checks a hand-rolled loop would need:RefreshSessions:Enabledfalse logs and returnsfalse(:90-94, the comment at:88-89notes registration is already gated on the flag and this is for a host that registers the service by hand), andRetentionDays <= 0logs and returnsfalsetoo (:96-100), the documented way to keep sessions forever; the base class skips the cycle entirely when this getter answersfalse.ExecuteCycleAsyncdelegates toPurgeAsync(:107), andLogCycleFailureroutes an uncaught exception from a cycle to the source-generatedLogCleanupErrormessage (:110), so one bad sweep is logged and the loop carries on rather than ending the service. PurgeAsync(RefreshSessionCleanupService.cs:118-148) computes the cutoff from the injected clock (:120), opens a scope and resolves the registry, resolver and context factory from it (:122-125).- Before deleting anything it checks
context.Model.FindEntityType(typeof(RefreshSession))and, on a miss, logs a warning naming the configured data source and returns (RefreshSessionCleanupService.cs:131-135). The comment at:128-130gives the operator-experience reason: a source can be reachable and still not map the table, and saying so once per sweep beats a translation error the operator has to decode. - The delete runs through
BatchedDelete.DeleteAsync<RefreshSession, Guid>over a two-armed predicate (RefreshSessionCleanupService.cs:141-147, predicate:143-144): revoked before the cutoff, or not revoked and expired before the cutoff. The method doc calls this "died" (:112-117), and both arms matter. A live session is never a candidate however old it is, and a session revoked minutes ago survives even if it expired long before, because that recent revocation is exactly what reuse detection reads. Each leg of the predicate has its own index,RevokedAtIndexNameandExpiresAtIndexNamefromRefreshSessionModelBuilderExtensions, so a batch seeks the dead rows instead of scanning the table; the sweep orders byId(:145) for a stable batch boundary (comment at:137-139).BatchedDeletereads ids and deletes by id in batches ofBatchSize = 1000(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Retention/BatchedDelete.cs:18), so a large backlog is many short statements rather than one long lock footprint. - The per-sweep count is logged unconditionally, zero included:
LogPurgedis passed as the report callback (RefreshSessionCleanupService.cs:146), whichBatchedDeletecalls exactly once with the total actually removed, even when a batch throws or the sweep is cancelled (BatchedDelete.cs:32-34,:54-57). The comment atRefreshSessionCleanupService.cs:139-140gives the reason: a "only when it deleted something" log cannot tell an operator that retention is running at all.[Rubric §13, Observability and Operability]assesses precisely that distinction. ResolveDataSourceKey(RefreshSessionCleanupService.cs:155-156) callsFrameworkTableTargets.ResolveHome<RefreshSession>, the same callEFRefreshSessionStoremakes, and its doc says why (:150-154): the sweep must never visit a different database than the store reads.- The five log messages are source-generated
[LoggerMessage]partials (RefreshSessionCleanupService.cs:158-171), which is why the class ispartial.
- Why it's built this way: retention bounds reuse detection, and the class doc is explicit about the trade (
RefreshSessionCleanupService.cs:26-32). BR-206 catches a replayed refresh token by finding its revoked row and revoking the whole family; a rotation chain older than the window is gone, so a replay of a token that old reads as an unknown token and fails alone instead of signalling reuse. The default window of 30 days (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:72, constrained to 0 through 3650 at:71) is far past the default refresh-token lifetime, so every token still capable of being replayed still has its row, and a host that shortensRefreshSessions:RetentionDaysbelowJwt:RefreshTokenExpirationDaysis choosing to lose that signal. Unlike the outbox, sessions live in exactly one physical source, which is why the sweep resolves one database rather than iterating them (:35-39). The sweep is the retention half of the 2026-08-27 revision of ADR-097. - Where it's used: registered as a hosted service only when
RefreshSessions:Enabledis true, read straight off configuration at registration time (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:241-245). The comment there gives the reason for the conditional (:237-240): registering it unconditionally would start a sweep in every service of a modular host, all but one of which has noRefreshSessionstable to sweep. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Auth/RefreshSessionCleanupServiceTests.cs, which exercises both disabled paths (:49,:68), the retention predicate (:105,:126), the zero-count log (:157), the unmapped-table warning (:171), the registration gate (:184,:196) and the source resolution (:210,:224). - Caveats / not-in-source: the default interval is 6 hours (
MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:80, constrained to 1 through 168 at:79), and because the loop waits one full interval before its first sweep, a host that restarts more often than the configured interval never sweeps. Nothing in the service compensates for that. The one-replica-per-interval behavior depends on anIDistributedLockbeing registered (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:115registers one withTryAddSingleton); in a container without one,cycleLockstaysnulland every replica sweeps, which the idempotent purge tolerates.
ColumnWidth
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/ColumnWidth.cs:4· Level 0 · class (internal static)
- What it is: an internal static helper with one method,
Truncate(string? value, int maxLength), that cuts a string to a column's maximum length while preservingnull(ColumnWidth.cs:4-12). - Depends on: nothing beyond the BCL
stringindexer and range operator. - Concept introduced, a defensive width guard for audit and command persistence rather than a value-object mapping. Both call sites write free-form diagnostic text (a trace ID, a CLR type name, a property key, a joined key string) into fixed-width columns where a value produced at runtime could exceed the column's declared size. Rather than let SQL reject the write or truncate silently at the provider,
Truncateclips the string before it reaches EF:value is null || value.Length <= maxLength ? value : value[..maxLength](ColumnWidth.cs:10-11). Anullinput passes straight through, so an absent value is never coerced into an empty string. - Walkthrough
Truncate(ColumnWidth.cs:10-11): a single expression-bodied method; no allocation happens when the value already fits.
- Why it's built this way: the callers (an audit interceptor and internal command processing) run outside a validated domain type, so nothing upstream already guarantees the string fits its column;
ColumnWidth.Truncateis the one place that guarantee is enforced before the row is written. - Where it's used:
AuditTrailSaveChangesInterceptortruncates a correlation ID, tenant ID, entity type name, property name, and joined key string through it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:233-234,294,363,748);ScheduledJobRunnerandInternalCommandProcessorcall it for the same reason at their own persistence boundaries.
StronglyTypedIdValueComparer<TSelf>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/StronglyTypedIdValueConverter.cs:57· Level 0 · class (public sealed)
- What it is: the EF Core
ValueComparer<TSelf>paired withStronglyTypedIdValueConverter<TSelf, TValue>whenever a host opts a strongly typed identifier into persistence, so EF's change tracker compares two identifier instances by their wrapped value instead of by reference (StronglyTypedIdValueConverter.cs:57-70). - Depends on:
TSelf's ownEquals/GetHashCodeviaEqualityComparer<TSelf>.Default(:33); EF Core'sValueComparer<T>fromMicrosoft.EntityFrameworkCore.ChangeTracking(NuGet,:1). - Concept introduced, telling EF how to compare a wrapper type for change detection.
ValueComparer<T>takes three delegates: an equality check, a hash function, and a snapshot function. BecauseTSelfhere is constrained tostruct(:26) and identifier wrappers are readonly record structs by convention, value equality is already correct and cheap, so the comparer forwards straight toEqualityComparer<TSelf>.Defaultfor both equality and hashing, and returns the identifier itself as its own snapshot (identifier => identifier,:35). Without an explicit comparer EF Core would fall back to its own default, which for a non-primitive CLR property type would not know how to unbox and compare the wrapped value the wayStronglyTypedIdValueConverterexpects on the provider side.[Rubric §8, Data Architecture]covers this: a strongly typed identifier is only transparent to EF's change tracking because the comparer is registered alongside the converter, not instead of it. - Walkthrough
- Constructor (
:31-37): passes three lambdas to theValueComparer<TSelf>base:(left, right) => EqualityComparer<TSelf>.Default.Equals(left, right)for equality,identifier => identifier.GetHashCode()for hashing, andidentifier => identifierfor the snapshot, since a value-type identifier needs no deep copy to snapshot safely.
- Constructor (
- Why it's built this way:
StronglyTypedIdModelConfiguration.Applyalways registers this comparer together with the converter throughHaveConversion(converterType, comparerType)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/StronglyTypedIdModelConfiguration.cs:38-45), so a consumer adopting a strongly typed identifier (ADR-115) never has to write or register this class directly. - Where it's used:
StronglyTypedIdModelConfiguration.Applyconstructs it viatypeof(StronglyTypedIdValueComparer<>).MakeGenericType(identifierType)for every identifier a host declares (StronglyTypedIdModelConfiguration.cs:40-41); its round trip is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/StronglyTypedIdPersistenceTests.cs.
UnknownStoredValue
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/UnknownStoredValue.cs:17· Level 0 · class (internal static)
- What it is: an internal static helper with one generic method,
Throw<T>(object storedValue), that is the single read-leg failure for every value converter that rebuilds a closed set (a smart-enumeration member, a currency) from a stored column (UnknownStoredValue.cs:3-8,:17-29). - Depends on: only the BCL
InvalidOperationExceptionandtypeof(T).Name(UnknownStoredValue.cs:25-28). - Concept introduced, failing loudly at the read instead of materializing a
null. A converter's read leg is an expression tree, and an expression tree cannot hold athrowexpression (remarksUnknownStoredValue.cs:10-11). A read leg that looks a stored value up in a closed set therefore has two choices: hand back the lookup result's nullableValue(a row holding a value no member declares then materializes anullthat surfaces later as aNullReferenceExceptionfar from the read, or as a silently wrong aggregate,:5-7), or call an ordinary method that throws.Throw<T>is that method. It is typed to returnTalthough it never returns (:22,:24), so a read leg can place it on the right of a??:FromValue(value).Value ?? UnknownStoredValue.Throw<TEnumeration>(value). Only a value written outside EF reaches it (a manual script, a data fix, a member removed after rows were written); every value the write leg produces round-trips (:11-13).[Rubric §8, Data Architecture]covers this: a stored value outside the closed set is treated as a data defect, reported at the point of read with the offending value named. - Walkthrough
Throw<T>(UnknownStoredValue.cs:24-28): expression-bodied, it always throwsInvalidOperationExceptionwith the messageThe stored value '{storedValue}' does not match any {typeof(T).Name}., followed by the two ways such a value arises and the remedy: "fix the row or restore the member".
- Why it's built this way: one helper keeps the verdict and the wording identical across every converter, and the remarks note that it matches the JSON converters, which also throw on an unknown value (
UnknownStoredValue.cs:13-14). It isinternalbecause only the framework's own converters and mappings call it. - Where it's used: the read legs of
EnumerationValueConverter<TEnumeration>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/EnumerationValueConverter.cs:47) andEnumerationNameValueConverter<TEnumeration>(EnumerationValueConverter.cs:88), and theMoney.Currencycode mapping inEntityTypeBuilderExtensions, where a non-empty stored code thatCurrency.FromCodedoes not recognize throws through it while an empty code still maps to the no-currency sentinel (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeBuilderExtensions.cs:84-89). The converter tests assert the message names the value and the type (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/EnumerationValueConverterTests.cs:59-68,:70-81through a real SQLite read,:107-115for the name converter).[104-smart-enums-as-opt-in-capability.md]records smart enumerations as an opt-in capability.
UtcDateTimeConverter
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/UtcDateTimeConverter.cs:25· Level 0 · class (internal sealed)
- What it is: an internal
ValueConverter<DateTime, DateTime>that normalizes everyDateTimewritten to PostgreSQL toDateTimeKind.Utc, and stamps the same kind back onto values read from the column (UtcDateTimeConverter.cs:25-40). - Depends on: only the BCL
DateTime/DateTimeKindand EF Core'sValueConverter<TModel, TProvider>(UtcDateTimeConverter.cs:1, implied by the file's imports). - Concept introduced, a provider-specific kind fixup that is not a value-object mapping. Unlike the converters above it, this one maps
DateTimeto itself: the model and provider CLR types are identical, and the transformation is purely about theKindflag Npgsql checks before it will accept atimestamp with time zonewrite.[Rubric §8, Data Architecture]covers exactly this: the framework's committed answer to "everyDateTimeis mappedtimestamp with time zone... never the process-wideNpgsql.EnableLegacyTimestampBehaviorswitch" (seeMMCA.Common/CLAUDE.md, Multi-Database Strategy) is a per-property converter rather than a global legacy-behavior opt-out, so the fix is scoped to PostgreSQL alone and does not alter how SQL Server, SQLite, or Cosmos treatDateTime. - Walkthrough
- Public constructor on an internal type (
:58-65): the class doc comment states the reason directly (:60-64): EF instantiates a named converter throughActivator.CreateInstance, which requires a PUBLIC parameterless constructor even when the enclosing type is internal. - Write leg (
:67-69):value.Kind == DateTimeKind.Local ? value.ToUniversalTime() : DateTime.SpecifyKind(value, DateTimeKind.Utc). ALocalvalue is genuinely converted; anything else (Utcor the defaultUnspecified) is relabeled asUtcwithout shifting the clock value, on the assumption that anUnspecifiedvalue already represents UTC wall-clock time. - Read leg (
:70):value => DateTime.SpecifyKind(value, DateTimeKind.Utc), stampingUtcback onto whatever Npgsql returns, since a round-tripped value otherwise comes back asUnspecified.
- Public constructor on an internal type (
- Why it's built this way: PostgreSQL's
timestamp with time zonecolumn type requires the .NET value to carryDateTimeKind.Utc(or Npgsql rejects it) onceEnableLegacyTimestampBehavioris off; wrapping everyDateTimeproperty in this converter keeps that requirement satisfied without touching call sites in entity configurations. - Where it's used:
PostgreSQLDbContextapplies it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/PostgreSQLDbContext.cs:1);MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/PostgreSQLDbContextModelTests.cspins its round trip across five assertions.[113-postgresql-as-a-first-class-engine.md]records PostgreSQL's adoption as a first-class engine.
StronglyTypedIdValueConverter<TSelf, TValue>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/StronglyTypedIdValueConverter.cs:33· Level 3 · class (public sealed)
- What it is: the EF Core
ValueConverter<TSelf, TValue>that stores a strongly typed identifier as the primitive it wraps and rebuilds the wrapper on read, so adopting the wrapper leaves the backing column (anint,bigint,uniqueidentifier, ornvarchar) unchanged (StronglyTypedIdValueConverter.cs:33-35, class doc:7-11). - Depends on:
IStronglyTypedId<TSelf, TValue>(the constraint onTSelf,:29-30) and its staticFromfactory (:142); EF Core'sValueConverter<TModel, TProvider>(NuGet,:2). - Concept introduced, a pre-convention identifier mapping that never becomes a migration. A host does not apply this converter property by property:
services.AddStronglyTypedIds(typeof(OrderId).Assembly)registers every declared identifier as a pre-convention type mapping onApplicationDbContext.ConfigureConventions(class doc:13-19), whichStronglyTypedIdModelConfiguration.Applyimplements by constructing this converter generically per identifier type (StronglyTypedIdModelConfiguration.cs:38-45) and pairing it withStronglyTypedIdValueComparer<TSelf>. Pre-convention is the load-bearing detail (class doc:14-19): the provider CLR type is known before EF picks a value-generation strategy, so a wrappedintkey still maps to a SQL Server IDENTITY column and a wrappedGuidkey still takes its client-side generator.[Rubric §4, Domain-Driven Design]assesses whether identifiers carry domain meaning rather than being bare primitives; wrapping is the recorded opt-in alternative to the identifier-type aliases (ADR-115, seeMMCA.Common/CLAUDE.md, Entity Model), on the same footing smart enumerations sit on.[Rubric §8, Data Architecture]covers the storage-shape guarantee: nothing in the schema changes when a consumer adopts the wrapper. - Walkthrough
- Type parameters and constraints (
:28-30):ValueConverter<TSelf, TValue>withwhere TSelf : struct, IStronglyTypedId<TSelf, TValue>andwhere TValue : notnull, IEquatable<TValue>. - Constructor (
:135-138):base(id => Unwrap(id), value => Wrap(value)), routed through static helpers rather than inline lambda bodies because, per the class doc (:21-24), a static abstract interface member (TSelf.From) cannot be invoked inside an expression tree. Unwrap(:140):identifier.Value, reading the wrapped primitive straight off the identifier.Wrap(:142):TSelf.From(value), the static-abstract factory every strongly typed identifier implements throughIStronglyTypedId<TSelf, TValue>.
- Type parameters and constraints (
- Why it's built this way: the domain wants identifiers that cannot be confused across aggregate boundaries even though they share the same wrapped primitive type; the database wants the same column it already had. The pre-convention
ConfigureConventionshook satisfies both without a per-propertyHasConversioncall at every entity configuration, and shipping the pair (converter + comparer) from the framework means the value-generation strategy for a wrapped key is never silently lost. - Where it's used:
StronglyTypedIdModelConfiguration.Applyconstructs it viatypeof(StronglyTypedIdValueConverter<,>).MakeGenericType(identifierType, valueType)for every identifier a host declares (StronglyTypedIdModelConfiguration.cs:38-45); its round trip is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/StronglyTypedIdPersistenceTests.cs.[115-strongly-typed-identifiers-opt-in.md]documents the feature; nothing inSource/adopts a wrapper today (MMCA.Common/CLAUDE.md, Entity Model), so production usage remains ahead of demand.
EnumerationNameValueConverter<TEnumeration>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/EnumerationValueConverter.cs:77· Level 4 · class (public sealed)
- What it is: the text-column sibling of
EnumerationValueConverter<TEnumeration>, aValueConverter<TEnumeration, string>that stores a smart-enumeration member as itsNameand rebuilds the member from that name on read (class docEnumerationValueConverter.cs:52-58, class:77-91). - Depends on:
Enumeration<TEnumeration>(the generic constraint,EnumerationValueConverter.cs:78), itsNameproperty (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Enumeration.cs:101) and its staticFromNamefactory (Enumeration.cs:142);Result<T>indirectly, becauseFromNamereturns one; EF Core'sValueConverter<TModel, TProvider>(NuGet,EnumerationValueConverter.cs:1). - Concept reinforced, choosing the provider type to match the column that already exists. The
HasConversion-over-OwnsOnemechanism is the one taught atEnumerationValueConverter<TEnumeration>; what changes is which existing column shape it preserves. A CLR enum mapped withHasConversion<string>()already stores member names as text, so swapping that enum for a smart enumeration through theintconverter would be a column type change plus a data rewrite. StoringNameinstead keeps the same text column and the same stored values, which the class doc states as its reason for existing (EnumerationValueConverter.cs:52-58).[Rubric §4, Domain-Driven Design]assesses whether the domain models concepts as behavior-carrying types; this converter removes the migration cost for the case where the old enum was persisted by name.[Rubric §8, Data Architecture]covers the storage-shape guarantee: neither the column type nor any stored value changes. - Walkthrough
- Type parameters and constraint (
EnumerationValueConverter.cs:77-78):ValueConverter<TEnumeration, string>withwhere TEnumeration : Enumeration<TEnumeration>. - Constructor, write leg (
EnumerationValueConverter.cs:85):member => member.Name, the member's canonical declared name. - Constructor, read leg (
EnumerationValueConverter.cs:86-88):text => string.IsNullOrEmpty(text) ? null! : Enumeration<TEnumeration>.FromName(text).Value ?? UnknownStoredValue.Throw<TEnumeration>(text). Empty ornulltext short-circuits to anullmember. OtherwiseFromNamelooks the text up in a name dictionary built withStringComparer.OrdinalIgnoreCase(Enumeration.cs:88) and returns either the member or an invariant failure codedEnumeration.UnknownName(Enumeration.cs:147-151); on failure the??hands the text toUnknownStoredValue.Throw<T>, which throwsInvalidOperationExceptionnaming the value and the enumeration type. - The read-leg contract (class doc
EnumerationValueConverter.cs:68-73): the same as theintsibling's, with one carve-out. A NON-EMPTY name no member declares throws at the read; empty text, which no member declares and the write leg never writes, still materializes anullmember, because only a non-empty unknown value is a verdict about the data. - Facets stay at the call site (
EnumerationValueConverter.cs:60-66): the documented usage chains.HasMaxLength(32)and.IsRequired()next toHasConversion. There is no nullable name-converter counterpart in the file.
- Type parameters and constraint (
- Why it's built this way: a stored enum name is a legitimate existing schema, and rewriting it to integers only to adopt a richer domain type would be a migration with no domain benefit. Matching case-insensitively on read also tolerates stored text whose casing differs from the declared name, while the write leg always emits the canonical name.
- Where it's used: MMCA.Helpdesk's
TicketConfigurationmapsTicket.Status(theTicketLifecyclesmart enumeration) through it withHasMaxLength(32), with an inline comment recording that the column keeps the text it held when the property was the wire enum (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Infrastructure/Persistence/EntityConfiguration/TicketConfiguration.cs:42-47);MMCA.Helpdesk/Tests/Architecture/MMCA.Helpdesk.Architecture.Tests/Persistence/TicketStatusColumnTests.cs:41-45pins that choice. No entity configuration in MMCA.ADC or MMCA.Store uses it. Its unit tests pin the written name (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/EnumerationValueConverterTests.cs:85-93), the case-insensitive read (:95-103), an unknown non-empty name throwing with the value in the message (:107-115),nulland empty text materializingnull(:119-127), the round trip of every member (:129-144), thestringprovider type (:146-153), and a SQLite round trip (:155).[104-smart-enums-as-opt-in-capability.md]records smart enumerations as an opt-in capability.
EnumerationValueConverter<TEnumeration>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/EnumerationValueConverter.cs:38· Level 4 · class (public sealed)
- What it is: the shipped EF Core
ValueConverter<TEnumeration, int>that stores a smart-enumeration member as its integerValueand rebuilds the member when a row is read back (EnumerationValueConverter.cs:38). It is the packaged replacement for the two lambdas every entity configuration would otherwise hand-roll to map anEnumeration<TEnumeration>property. - Depends on:
Enumeration<TEnumeration>(the generic constraint,EnumerationValueConverter.cs:39), itsValueproperty (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Enumeration.cs:105) and its staticFromValuefactory (Enumeration.cs:121);Result<T>indirectly, becauseFromValuereturns one; EF Core'sValueConverter<TModel, TProvider>fromMicrosoft.EntityFrameworkCore.Storage.ValueConversion(NuGet,EnumerationValueConverter.cs:1). - Concept introduced, mapping a smart enumeration onto the column a CLR enum already used. A smart enumeration is a class, not a language
enum, so the naive EF answer isOwnsOne: the member becomes an owned entity type with its own columns, which turns "replace theenumproperty with a richer type" into a schema change and a migration.HasConversiontakes the other route. It keeps a single flat column and supplies a pair of expression trees: a write leg that turns the model value into the provider value, and a read leg that turns the provider value back. Because this converter's provider type isint(EnumerationValueConverter.cs:38), the backing column stays exactly the plain integer column a CLR enum was already persisted into, so adopting the smart enumeration in the domain changes nothing in the database. The class doc states this as the reason for the choice (EnumerationValueConverter.cs:6-11).[Rubric §4, Domain-Driven Design]assesses whether the domain models concepts as behavior-carrying types rather than primitives or bare enums; a framework-shipped converter removes the storage-cost argument against doing so.[Rubric §8, Data Architecture]assesses how deliberately the storage shape is chosen; the flatintcolumn keeps indexes, existing rows, and prior migrations untouched. - Walkthrough
- Type parameters and constraint (
EnumerationValueConverter.cs:38-39):ValueConverter<TEnumeration, int>withwhere TEnumeration : Enumeration<TEnumeration>, the curiously-recurring constraint that makesFromValueresolve to the concrete member type rather than to the base. - Constructor, write leg (
EnumerationValueConverter.cs:46):member => member.Value, the member's declared stable integer (Enumeration.cs:105). No validation happens here: a member reference is valid by construction, since the only members that exist are the ones the type declares. - Constructor, read leg (
EnumerationValueConverter.cs:47):value => Enumeration<TEnumeration>.FromValue(value).Value ?? UnknownStoredValue.Throw<TEnumeration>(value).FromValuelooks the value up in the type's interned member dictionary and returns a success result (Enumeration.cs:123-124) or an invariant failure codedEnumeration.UnknownValue(Enumeration.cs:126-130).Result<T>.Valueis declared nullable and returnsnullon failure rather than throwing (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Result.cs:194-195), so the??routes exactly the unknown-value case toUnknownStoredValue.Throw<T>, which throwsInvalidOperationExceptionnaming the value and the enumeration type. Athrowcannot appear inside the expression tree itself, which is why the failure lives in a helper method. - The read-leg contract, spelled out (
EnumerationValueConverter.cs:27-34): a stored value no member declares THROWS, the same verdict the JSON converter gives. Every value the write leg can produce round-trips, because the write leg can only persist an already-declared member; only a value written outside EF (a manual script, a data fix, or a member deleted from the enumeration after rows were written) fails, and it fails at the read instead of as anullmember far from it. - What it deliberately does not do (
EnumerationValueConverter.cs:19-20): requiredness, default value, and precision stay at the call site, because they differ per entity. The documented usage chains.IsRequired()next to theHasConversioncall (EnumerationValueConverter.cs:13-18). - One converter for required and optional properties (
EnumerationValueConverter.cs:20-25): EF never passes anullto a converter that does not convert nulls, so a NULL column stays anullmember and the reverse, with no nullable twin class. An optional property maps through the non-generic overload,.HasConversion((ValueConverter)new EnumerationValueConverter<Priority>()).IsRequired(false), because the generic overload compares the converter's non-nullable model type with the property's nullable one.
- Type parameters and constraint (
- Why it's built this way: the domain wants a type that can carry names, ordering, and behavior; the database wants the same integer column it already has.
HasConversionsatisfies both, and shipping the converter from the framework means every consumer gets the same interning behavior on read rather than a per-configuration lambda that might allocate a fresh instance. - Where it's used: no entity configuration in MMCA.Common, MMCA.ADC, or MMCA.Store maps a property through it today; the only callers are its unit tests, which pin the round trip (
MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/EnumerationValueConverterTests.cs:18-27), the column types (EnumerationValueConverterTests.cs:30-36), and the fact that the read leg resolves the interned singleton for every declared member rather than a copy (EnumerationValueConverterTests.cs:39-46, asserted withBeSameAs), an unknown value throwing with the value named in the message (EnumerationValueConverterTests.cs:59-68, and through a real SQLite read at:70-81), and an optional property keeping NULL as NULL on both legs while a present member round-trips (EnumerationValueConverterTests.cs:177-198). It is shipped ahead of demand.
EmailValueConverter
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/EmailValueConverter.cs:33· Level 5 · class (public sealed)
- What it is: the shipped EF Core
ValueConverter<Email, string>that stores anEmailvalue object as its normalized string and rebuilds the value object when a row is read back (EmailValueConverter.cs:33). It exists so no entity configuration has to hand-roll the same two lambdas. - Depends on:
Emailand itsCreatefactory (EmailValueConverter.cs:2,MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Contact/Email.cs:30);Result<T>indirectly, sinceCreatereturns one; EF Core'sValueConverter<TModel, TProvider>(NuGet,EmailValueConverter.cs:1). - Concept reinforced,
HasConversionoverOwnsOnefor a value object. The mechanism is the one taught atEnumerationValueConverter<TEnumeration>; what changes is the provider type. Here the column stays a plain string column (EmailValueConverter.cs:33), so a codebase can upgradestring EmailtoEmail Emailin the domain and change nothing in the database. That is the whole point of shipping the converter from the framework: the domain gets an invariant-protected type (Email.Createvalidates throughEmailInvariantsatEmail.cs:34and lowercases atEmail.cs:39), while storage keeps the simplest possible shape.[Rubric §4, Domain-Driven Design]assesses whether the domain expresses concepts as rich types rather than primitives; a shipped converter removes the usual excuse for keeping an email as a bare string.[Rubric §15, Best Practices & Code Quality]assesses whether a change of this kind ripples: the converter is written once in Infrastructure and reused across the repos rather than copy-pasted per configuration. - Walkthrough
- Type parameters (
EmailValueConverter.cs:33):ValueConverter<Email, string>, so EF knows the CLR (model) type isEmailand the provider (column) type isstring. - Constructor, write leg (
EmailValueConverter.cs:40):email => email.Valuepersists the already-normalized lowercase string thatEmail.Createproduced (Email.cs:39). No validation happens here because a constructedEmailis valid by construction. - Constructor, read leg (
EmailValueConverter.cs:41):value => Email.Create(value).Value!. The read leg deliberately trusts the column.Result<T>.Valueis nullable and returnsnullon failure rather than throwing (Result.cs:194-195), so the null-forgiving!means a row whose stored text does not validate materializes anullreference for that property instead of blowing up model materialization. The class doc states the contract explicitly (EmailValueConverter.cs:24-31): every value the write leg can produce round-trips, because the write leg can only persist an already-validatedEmail; only a value written outside EF (a manual script, a data fix) can break it. - What the converter deliberately does not do (
EmailValueConverter.cs:20-22): column facets (max length,IsUnicode, requiredness) stay at the call site, because they differ per entity. The documented usage pattern chains them next to theHasConversioncall (EmailValueConverter.cs:14-19).
- Type parameters (
- Why it's built this way: two forces meet here. The domain wants a type that cannot hold an invalid address; the database wants a column that indexes and migrates like the
nvarcharit already was.HasConversionsatisfies both, and shipping the converter pair from Common (rather than documenting the lambdas) means every consumer gets the same normalization and the same read-leg contract.Emailitself names this class and its nullable sibling in its own doc comment (Email.cs:7-14), so the intended mapping is discoverable from the domain type. - Where it's used: ADC's Identity
UserConfigurationmapsUser.Emailthrough it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:22), and Store uses it for bothUser.Email(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:24) andCustomer.Email(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Infrastructure/Persistence/EntityConfiguration/CustomerConfiguration.cs:36). The Store call sites carry an inline comment recording that the mapping isHasConversionand notOwnsOneprecisely so the column shape stays a plainnvarchar(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:21-22). Round-trip behavior is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/EmailValueConverterTests.cs:16.
NullableEmailValueConverter
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conversions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/EmailValueConverter.cs:60· Level 5 · class (public sealed)
- What it is: the optional-property counterpart of
EmailValueConverter, aValueConverter<Email?, string?>for an entity property typedEmail?(EmailValueConverter.cs:60). - Depends on: the same
Emailvalue object and EF Core'sValueConverter<TModel, TProvider>; see the sibling above for the shared shape. - Concept reinforced, keeping "absent" absent. The interesting part of a nullable converter is what it refuses to do. Both legs short-circuit on
null(EmailValueConverter.cs:67-68): the write leg emitsnullrather than an empty string, and the read leg returnsnullrather than callingEmail.Create(null)and producing a failed result. Without those guards, "no email" would silently become either an empty-string column value (which then fails validation on the way back) or a null reference produced by a failed factory call. Note the read leg here uses plain.Value(EmailValueConverter.cs:68), not the null-forgiving.Value!of the non-nullable sibling, because the model type is already nullable.[Rubric §8, Data Architecture]covers nullability as a modeled fact rather than an accident: NULL stays NULL end to end. - Walkthrough
- Write leg (
EmailValueConverter.cs:67):email => email == null ? null : email.Value. - Read leg (
EmailValueConverter.cs:68):value => value == null ? null : Email.Create(value).Value. - Usage shape (
EmailValueConverter.cs:52-57): the doc comment pairs it with.IsRequired(false)and a call-siteHasMaxLength, exactly as the non-nullable sibling keeps facets outside the converter.
- Write leg (
- Why it's built this way: a single converter cannot serve both
EmailandEmail?, because EF resolves the converter against the declared CLR property type. Shipping the pair keeps the choice explicit at the configuration and avoids per-entity nullable lambdas. - Where it's used: ADC's
SpeakerConfigurationmaps the optionalSpeaker.Emailthrough it (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Infrastructure/Persistence/EntityConfiguration/Speakers/SpeakerConfiguration.cs:43), with the length facet coming fromSpeakerInvariants.EmailMaxLengthat the call site (SpeakerConfiguration.cs:44). Null pass-through is covered atMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/EmailValueConverterTests.cs:63.
ConnectionStringSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/ConnectionStringSettings.cs:12· Level 0 · class (sealed)
What it is: the class bound from the top-level
ConnectionStringssection, one connection string per supported engine (SQL Server, PostgreSQL, SQLite, Cosmos) plus the Cosmos database name and a migrations assembly for each of the two migrated relational engines. It describes theDefaultphysical data source, the one every unmapped logical name collapses onto.Depends on: nothing first-party and nothing beyond
stringfrom the BCL, which is what puts it at Level 0. It is read byDataSourceResolverand cross-checked byConnectionStringSettingsValidator.Concept introduced, fail-fast configuration where the rule spans two sections.
[Rubric §15, Best Practices & Code Quality]assesses whether misconfiguration is caught early.AddOptions<T>().Bind(...).ValidateDataAnnotations().ValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:74-77) is the pattern every validated settings class uses, and ADR-070 makes it the required form: annotations run during host startup rather than lazily on first resolution.ValidateOnStart()is the load-bearing call.What this type teaches on top of that is the limit of the annotation approach. No property here is
[Required], and the class doc says why (ConnectionStringSettings.cs:5-10): SQL Server is the default engine, but a host may run entirely on SQLite, PostgreSQL, or Cosmos and may declare its databases underDataSourcesinstead of this section. A[Required]attribute can only see one property on one class, so the real invariant ("the host can reach SOME database") is expressed as anIValidateOptions<T>implementation registered alongside the binding,ConnectionStringSettingsValidator(DependencyInjection.cs:84-85).[Rubric §8, Data Architecture]: the rule spans both configuration shapes precisely because the physical topology is a deployment decision, not a compile-time one.Walkthrough: one static field and seven
{ get; init; }strings.SectionName = "ConnectionStrings"(ConnectionStringSettings.cs:15), reusing ASP.NET Core's own conventional section soGetConnectionString(...)and this class read the same data.CosmosConnectionString(ConnectionStringSettings.cs:18), empty by default.CosmosDatabaseName(ConnectionStringSettings.cs:25), the one property with a non-empty default,"MMCA". Its doc comment spells out the override path explicitly: a Cosmos host that needs a different database setsConnectionStrings:CosmosDatabaseName, or a per-sourceDataSources:<Name>:CosmosDatabaseName, explicitly (ConnectionStringSettings.cs:19-24).PostgreSQLConnectionString(ConnectionStringSettings.cs:28), empty by default.PostgreSQLMigrationsAssembly(ConnectionStringSettings.cs:37), empty by default. Its doc states the same rulePhysicalDataSource.UsesMigrationsimplements: when empty the PostgreSQL source is created outright instead of migrated, the SQLite rule rather than the SQL Server one, because PostgreSQL support ships with no host that already depends on being migrated (ConnectionStringSettings.cs:29-36).SqliteConnectionString(ConnectionStringSettings.cs:40), documented as typically a file path.SQLServerConnectionString(ConnectionStringSettings.cs:43), the production engine's connection string.SQLServerMigrationsAssembly(ConnectionStringSettings.cs:49), empty by default, which makes EF fall back to the DbContext assembly (ConnectionStringSettings.cs:45-48).- The registered validator is the interesting half.
ConnectionStringSettingsValidator.Validatesucceeds when either the top-level section names a database on any of the four engines (ConnectionStringSettingsValidator.cs:57-61) or any namedDataSourcesentry does (ConnectionStringSettingsValidator.cs:68-74), and otherwise fails with a message that lists all four top-level settings plus the named-entry form because which one is missing depends on the host (ConnectionStringSettingsValidator.cs:38-44,ConnectionStringSettingsValidator.cs:47-54). Its remarks record the change of rule directly: this replaced a[Required]onSQLServerConnectionStringthat failed a legitimate SQLite-only host at startup (ConnectionStringSettingsValidator.cs:11-24).
Why it's built this way:
init-only properties make the bound settings immutable after startup, whichDataSourceResolverrelies on, since it classifies every physical source once in its constructor (DataSourceResolver.cs:65-78). Keeping the "some database" check at boot rather than at first query is what stops a host from reporting healthy while unable to serve a request (ConnectionStringSettingsValidator.cs:20-24).Where it's used: bound and validated in
AddInfrastructure(DependencyInjection,DependencyInjection.cs:74-85); consumed byDataSourceResolverthroughIOptions<ConnectionStringSettings>(DataSourceResolver.cs:66,DataSourceResolver.cs:73), which reads it while seeding each engine'sDefaultsource (DataSourceResolver.cs:261-296) and while applying the Cosmos database-name fallback (DataSourceResolver.cs:310-311).Caveats: the Cosmos database default was renamed from the application-specific
"AtlDevCon"(the ADC conference database name) to the neutral"MMCA"(ConnectionStringSettings.cs:25); every default on this class is now framework-neutral.
DataSourceEntrySettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceEntrySettings.cs:19· Level 0 · class (sealed)
- What it is: the shape of ONE named entry under the
DataSourcesconfiguration section, the per-logical-source counterpart to the top-levelConnectionStringsblock. It carries a connection string per engine plus four per-source overrides (Cosmos database name and a migrations assembly for each of the two migrated relational engines). - Depends on: nothing first-party and nothing beyond
stringfrom the BCL, which is why it sits at Level 0. It is aggregated byDataSourcesSettingsand read byDataSourceResolver. - Concept introduced, configuration as the physical-topology dial.
[Rubric §8, Data Architecture]assesses how the logical model maps onto physical stores;[Rubric §7, Microservices Readiness]assesses whether a module can be lifted out with its own database. The declarative half of that story isUseDatabaseAttribute, which names a logical source on an entity configuration. This class is the other half: it says what that logical name physically means in a given deployment. Nothing in the code decides the topology; the same compiled assemblies run as a one-database monolith or as N separate databases depending on how many entries exist here.[Rubric §15, Best Practices & Code Quality]: because every property defaults tostring.Empty(DataSourceEntrySettings.cs:22-64), a partially filled entry is legal and each empty value falls back to the corresponding top-level value, so a host adds a database by adding one JSON object and nothing else. - Walkthrough: eight
{ get; init; }properties, all defaulting tostring.Empty.CosmosConnectionString(DataSourceEntrySettings.cs:22) andCosmosDatabaseName(DataSourceEntrySettings.cs:25), the Cosmos pair; the database name falls back to the top-levelCosmosDatabaseNamewhen empty (DataSourceResolverapplies that fallback atDataSourceResolver.cs:310-311and again atDataSourceResolver.cs:338-340).PostgreSQLConnectionString(DataSourceEntrySettings.cs:28), the PostgreSQL connection string for this source (ADR-113).PostgreSQLMigrationsAssembly(DataSourceEntrySettings.cs:37), with a fallback that is narrower than the SQL Server one (DataSourceEntrySettings.cs:30-36): when empty, a source that collapses ontoDefaulttakes the top-levelPostgreSQLMigrationsAssembly, but a separate named PostgreSQL source gets no migrations assembly unless its entry declares one, whereasSQLServerMigrationsAssemblyfalls back to the Default value with a warning.SqliteConnectionString(DataSourceEntrySettings.cs:40), the SQLite path (ADR-018 polyglot persistence).SqliteMigrationsAssembly(DataSourceEntrySettings.cs:55), and its doc is worth reading in full (DataSourceEntrySettings.cs:42-54): there is deliberately NO top-level fallback for it. The top-levelConnectionStringssection carries SQL Server and PostgreSQL migrations assemblies but no SQLite one, so a SQLite host declares its own here through an entry that collapses ontoDefault. Without that asymmetry a mixed-engine host would silently hand a relational-engine migrations assembly to a SQLite database.SQLServerConnectionString(DataSourceEntrySettings.cs:58), the production engine's connection string.SQLServerMigrationsAssembly(DataSourceEntrySettings.cs:64), the EF Core migrations assembly for THIS source, documented as falling back to the top-level value when empty (DataSourceEntrySettings.cs:60-63).- The resolver reads the relational pair through one engine-keyed switch,
GetMigrationsAssembly(DataSourceResolver.cs:445-452), stamps the SQLite or PostgreSQL value onto thePhysicalDataSourcevia its object initializer, only for the matching engine (DataSourceResolver.cs:475-477), and names the offending setting per engine when two logical names collapse onto one database with conflicting values (DataSourceResolver.cs:471-478). - The XML doc carries a worked
appsettings.jsonexample for aConferencesource (DataSourceEntrySettings.cs:9-18), which is the fastest way to see the intended shape.
- Why it's built this way:
init-only properties make a bound entry immutable after startup, and the "empty means inherit" rule is what keeps the single-database default intact: an app that configures noDataSourcessection behaves exactly as it did before the section existed (ADR-006). - Where it's used: bound as the value type of the dictionary that
AddInfrastructurereads withconfiguration.GetSection(DataSourcesSettings.SectionName).Get<Dictionary<string, DataSourceEntrySettings>>()(DependencyInjection.cs:89-91); consumed byDataSourceResolverwhen it classifies logical names into physical sources (DataSourceResolver.cs:327-341) and when it tests whether any entry names a database for an engine (DataSourceResolver.cs:195-200), and byConnectionStringSettingsValidatorwhen it looks for any configured database (ConnectionStringSettingsValidator.cs:68-74).
DefaultSeed
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceResolver.cs:237· Level 0 · record (sealed, private nested)
- What it is: a three-field carrier describing what the
Defaultphysical source of one engine is built from:ConnectionString,MigrationsAssembly, andCosmosDatabaseName(DataSourceResolver.cs:237). It exists only insideDataSourceResolver, where it is computed once per engine and then threaded through the four private methods that build that engine's map. - Depends on: nothing first-party. It holds three
stringvalues, all of which may legitimately be empty. It is produced fromConnectionStringSettingsandDataSourcesSettingsbyResolveDefaultSeed(DataSourceResolver.cs:262-297). - Concept introduced, the two-branch answer to "which database is Default".
[Rubric §8, Data Architecture]assesses whether the mapping from configuration to physical storage is explicit and has one owner;[Rubric §15, Best Practices & Code Quality]assesses whether a rule that several methods depend on is stated once instead of recomputed at each use.Defaultis the logical name every framework-owned table resolves to (outbox, inbox, scheduled jobs, audit trail), so "what is Default" has to have an answer even in a host that never wrote a top-levelConnectionStringsentry. The seed is that answer, and computing it into a record rather than passing three loose strings is what letsClassifyEntries,RegisterDefaultSource, andRegisterNamedSourceall agree on it (DataSourceResolver.cs:221-228). - Walkthrough
ConnectionString(DataSourceResolver.cs:234,DataSourceResolver.cs:237) is the connection theDefaultsource uses, and is empty when the engine is unconfigured. Branch one ofResolveDefaultSeedtakes it straight from the top-level section when that section names a connection for the engine (DataSourceResolver.cs:267-277). Branch two applies only when the top-level value is absent: the namedDataSourcesentries are filtered down to the ones carrying a connection for this engine (DataSourceResolver.cs:279-281), their connection identities are counted distinctly (DataSourceResolver.cs:283-286), and when exactly ONE distinct database is named that database becomesDefault(DataSourceResolver.cs:291-295). With several distinct databases and no top-level value there is no single answer, so the seed stays empty (DataSourceResolver.cs:296) and a genuinely multi-database host names the shared one by adding aDataSources:Defaultentry.MigrationsAssembly(DataSourceResolver.cs:235) is populated only on the top-level branch, and only for SQL Server:ConnectionStringscarries no SQLite equivalent, and handing a SQLiteDefaultsource the SQL Server value in a mixed-engine host would scaffold the wrong schema (DataSourceResolver.cs:267-270). Branch two deliberately leaves it empty (DataSourceResolver.cs:288-290): every entry it considered has the seed's own connection identity, so those entries all collapse ontoDefaultand contribute their declared assemblies throughAddExplicitMigrationsAssemblies, conflicts included. A test pins that the single named entry's assembly still reaches theDefaultsource that way (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/DataSourceResolverTests.cs:374).CosmosDatabaseName(DataSourceResolver.cs:236) is the database name entries fall back to when they declare none of their own, applied byCosmosDatabaseNameOf(DataSourceResolver.cs:311-312) and again inline while classifying entries (DataSourceResolver.cs:338-340).
- Why it's built this way: branch two cannot change an existing host's routing, because it fires
only where the top-level value is absent (
DataSourceResolver.cs:244-250). That is the additive-by-construction property the whole data-source layer is built on (ADR-006): a host that declares its database only underDataSourcesgets a workingDefault, and a host that declares it the old way resolves exactly as it always did. - Where it's used: only within
DataSourceResolver.BuildEngineMapcomputes it (DataSourceResolver.cs:221) and passes it toClassifyEntries(DataSourceResolver.cs:222),RegisterDefaultSource(DataSourceResolver.cs:223), andRegisterNamedSource(DataSourceResolver.cs:227). The two behaviors it decides are pinned byDataSourceResolverTests.cs:374andDataSourceResolverTests.cs:395. - Caveats / not-in-source: a private nested type. It is inventoried because private nested types are, but nothing outside the resolver can name it, and it never leaves the constructor's call graph.
DataSourcesSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourcesSettings.cs:13· Level 1 · class (sealed)
- What it is: the bound
DataSourcessection as a whole, a read-only dictionary of logical source name toDataSourceEntrySettings. It is the configuration input to database-per-microservice routing. - Depends on:
DataSourceEntrySettingsandDataSourceKey.DefaultNamefrom the Application layer (DataSourceKey), referenced by its fully qualified nameApplication.Interfaces.Infrastructure.Persistence.DataSourceKey(DataSourcesSettings.cs:34). - Concept introduced, a settings class that validates in its own constructor. Most settings types
here are inert bags validated by data annotations. This one is different, and the reason is stated in
its own doc: a root-level dictionary section does not bind through the options pipeline, so
AddInfrastructurebuilds the instance by hand fromconfiguration.GetSection(...).Get<Dictionary<string, DataSourceEntrySettings>>()and registers it as a singleton (DataSourcesSettings.cs:8-11,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:89-92). With no options pipeline there is noValidateOnStart, so the constructor becomes the fail-fast gate.[Rubric §15, Best Practices & Code Quality]: rejecting a reserved name at construction is the same guaranteeValidateOnStartwould have given, implemented where the type can enforce it itself.[Rubric §8, Data Architecture]: the reserved-name rule protects a real invariant,Defaultis configured through the top-levelConnectionStringssection, and letting someone also declare aDataSources:Defaultentry would create two competing definitions of the same physical source. - Walkthrough
SectionName = "DataSources"(DataSourcesSettings.cs:16).- The constructor takes an optional
IReadOnlyDictionary<string, DataSourceEntrySettings>?(DataSourcesSettings.cs:23) and substitutes an empty ordinal-comparer dictionary when it is null (DataSourcesSettings.cs:25), so "noDataSourcessection" is a first-class state rather than a null check at every call site. - It then walks every key (
DataSourcesSettings.cs:27-40) and throwsInvalidOperationExceptiontwice: on a blank or whitespace name (DataSourcesSettings.cs:29-32), and on any name equal toDataSourceKey.DefaultNameunderOrdinalIgnoreCase(DataSourcesSettings.cs:34-39). The second message is unusually good operator guidance: it names the offending entry and tells the reader that theDefaultsource is configured via the top-levelConnectionStringssection, so remove or rename the entry. Sources(DataSourcesSettings.cs:44), the get-only dictionary the resolver reads.
- Why it's built this way: throwing during host construction is the earliest possible point at which
a duplicate
Defaultdefinition can be caught; the alternative is a routing bug that surfaces as data landing in the wrong database (ADR-006). - Where it's used: constructed and registered as a singleton in
AddInfrastructure(DependencyInjection.cs:89-92), immediately beforeDataSourceResolverandEntityDataSourceRegistry(DependencyInjection.cs:93-94). It is consumed by the resolver's constructor (DataSourceResolver.cs:67,DataSourceResolver.cs:69-77), by its "is any database configured for this engine" test (DataSourceResolver.cs:195-200) and its classification pass (DataSourceResolver.cs:328-341), and byConnectionStringSettingsValidator, which takes it as an optional constructor dependency so that a container binding the settings withoutAddInfrastructurestill validates (ConnectionStringSettingsValidator.cs:26-30,ConnectionStringSettingsValidator.cs:68-74). - Caveats: the key comparison for reservation is
OrdinalIgnoreCase(DataSourcesSettings.cs:34) while the default backing dictionary usesStringComparer.Ordinal(DataSourcesSettings.cs:25). The dictionary that configuration binding actually supplies is created by the binder, so its comparer is not determined by this file.
ConnectionStringSettingsValidator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/ConnectionStringSettingsValidator.cs:30· Level 2 · class (sealed, internal)
What it is: the startup validator for
ConnectionStringSettings. It enforces exactly one rule: the host must be able to reach at least one database, declared either in the top-levelConnectionStringssection or on a namedDataSourcesentry (ConnectionStringSettingsValidator.cs:5-9).Depends on:
DataSourcesSettingsas an OPTIONAL primary-constructor parameter (ConnectionStringSettingsValidator.cs:30) andConnectionStringSettingsas the validated type (ConnectionStringSettingsValidator.cs:31). Externals:Microsoft.Extensions.OptionsforIValidateOptions<T>andValidateOptionsResult.Concept introduced, the rule that cannot be an attribute. A data annotation can only see the object it decorates. This rule spans two independently bound configuration sections, and that is the whole reason the class exists. The class remarks say what it replaced: a
[Required]onConnectionStringSettings.SQLServerConnectionString, which encoded "SQL Server is the only engine a host can boot on" (ConnectionStringSettingsValidator.cs:11-18). That stopped being true once a small application could run entirely on SQLite or Cosmos, declaring its databases through theDataSourcessection and leaving the top-level section empty; the annotation failed such a host at startup even though every one of its entities resolved to a configured database. The registration comment in the composition root makes the same point at the call site (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:79-83).[Rubric §17, DevOps & Deployment]assesses whether configuration is validated centrally rather than defensively at each read. The check runs once, at boot, underValidateOnStart, so no downstream component has to ask "did anyone configure a database".[Rubric §13, Observability and Operability]assesses whether a failure tells the operator what to do.NoDatabaseConfiguredMessageis aninternal const(ConnectionStringSettingsValidator.cs:38-44) rather than an inline string, and it lists all four top-level shapes (ConnectionStrings:SQLServerConnectionString,ConnectionStrings:PostgreSQLConnectionString,ConnectionStrings:SqliteConnectionString,ConnectionStrings:CosmosConnectionString), plus the named-entry form (DataSources:Tickets:SqliteConnectionString), because which one is missing depends on whether the host is a single-database monolith or a database-per-module one. The final sentence states the design decision itself: a host with no database at all cannot serve a request, so it fails here rather than on its first query.[Rubric §8, Data Architecture]shows up in what the rule deliberately does NOT weaken. A host with no connection string anywhere still fails to start (ConnectionStringSettingsValidator.cs:20-24). Silently booting one would trade a clear startup failure for anInvalidOperationExceptionon the first query, or worse, a service reporting healthy while unable to serve a single request.Walkthrough: one constant, the interface method, and two predicates.
- The primary constructor takes
DataSourcesSettings? dataSources = null(ConnectionStringSettingsValidator.cs:30). The default is what makes the validator constructible in a container that binds the settings without callingAddInfrastructure(ConnectionStringSettingsValidator.cs:26-29); such a container still gets the top-level check. NoDatabaseConfiguredMessage(ConnectionStringSettingsValidator.cs:38-44):internal const, so tests assert against the same string the host emits.Validate(string? name, ConnectionStringSettings options)(ConnectionStringSettingsValidator.cs:47-54): null-guards the options, then returnsSuccessif either predicate holds andFail(NoDatabaseConfiguredMessage)otherwise. Note the short-circuit||: one database anywhere is enough.HasTopLevelConnection(ConnectionStringSettingsValidator.cs:57-61): static, and usesIsNullOrWhiteSpacerather thanIsNullOrEmptyacross all four engine properties, which matters becauseConnectionStringSettingsinitialises each of them tostring.Emptyrather than leaving them null (ConnectionStringSettings.cs:18,ConnectionStringSettings.cs:28,ConnectionStringSettings.cs:40,ConnectionStringSettings.cs:43).HasNamedConnection(ConnectionStringSettingsValidator.cs:68-74): instance, because it reads the injected sources. It passes when ANY entry underDataSourcesnames a database on any of the four engines. The doc explains why one is enough: an entry carrying a connection string is a physical source the resolver registers, so the host has somewhere to read and write even with the top-level section empty (ConnectionStringSettingsValidator.cs:63-67).
- The primary constructor takes
Why it's built this way: this is one of the two custom
IValidateOptions<T>implementations the fail-fast configuration contract (ADR-070) records, the other beingTenancySettingsValidator. Relaxing the SQL Server requirement into a cross-section reachability rule is what made the polyglot persistence story (ADR-018) usable by a host that never touches SQL Server, without giving up the boot-time guarantee for the hosts that do.Where it's used: registered by
AddInfrastructurewithTryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<ConnectionStringSettings>, ConnectionStringSettingsValidator>())(DependencyInjection.cs:84-85), immediately after theValidateOnStartchain that binds the section (DependencyInjection.cs:74-77);TryAddEnumerable, like the tenancy validator, because two modules callingAddInfrastructuremust not run the same validation twice. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Settings/ConnectionStringSettingsValidatorTests.cs, which drives the validator directly for each engine and for the named-source shapes, and end to end through the realValidateOnStartchain including the SQLite-only host.Caveats: the type is
internal, so a consumer cannot subclass or replace it; a host needing extra connection-string rules registers its own additionalIValidateOptions<ConnectionStringSettings>.
IEntityDataSourceRegistry
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/IEntityDataSourceRegistry.cs:11· Level 2 · interface
- What it is: the contract for the eagerly-built registry that maps every configured entity type to
the physical database it lives in. Four members:
GetDataSourceKey(Type)(IEntityDataSourceRegistry.cs:17),GetDataSourceKey(string entityFullName)(IEntityDataSourceRegistry.cs:23),TryGetDataSourceKey(string, out DataSourceKey)(IEntityDataSourceRegistry.cs:29), andGetPhysicalSourcesInUse()(IEntityDataSourceRegistry.cs:35). - Depends on:
DataSourceKey, the(Engine, Name)pair every member trades in. - Concept introduced, eager entity-to-database mapping.
[Rubric §8, Data Architecture]assesses whether database routing is a deliberate, discoverable design rather than an accident of query order;[Rubric §7, Microservices Readiness]assesses whether a module can be lifted into its own service without rewriting application code. The doc comment (IEntityDataSourceRegistry.cs:5-10) states why the interface exists at all: it replaces a legacy lazy cache that was populated as a side effect of EF model building, so routing decisions (unit of work, navigation classification, outbox enumeration) no longer depend on a model having been built first.GetPhysicalSourcesInUse()returns the distinct databases this host actually uses, which is how migrations,EnsureCreated, and the outbox processor know which databases to touch (IEntityDataSourceRegistry.cs:31-35). The two strictGetDataSourceKeyoverloads are documented to throwInvalidOperationExceptionfor an unregistered entity (IEntityDataSourceRegistry.cs:16,IEntityDataSourceRegistry.cs:22), whileTryGetDataSourceKeyis the non-throwing probe used where a miss is legitimate, for example whenApplicationDbContextdecides whether an entity belongs in the model it is currently building (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:1098-1100). - Why it's built this way: database-per-service (ADR-006) needs every entity to resolve to exactly one physical source; deriving that map from configuration classes instead of from a built model turns a misconfiguration into a loud startup failure instead of a silent wrong-database query.
- Where it's used: implemented by
EntityDataSourceRegistryand registered as a singleton inAddInfrastructure(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:94). Consumers includeDbContextFactory(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:51),CrossDataSourceDegradeConvention(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/CrossDataSourceDegradeConvention.cs:36),DataSourceService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceService.cs:12), theOutboxProcessor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:69), theOutboxCleanupService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxCleanupService.cs:59), theAuditTrailCleanupJob(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailCleanupJob.cs:49), both model-building passes ofApplicationDbContext(ApplicationDbContext.cs:613,ApplicationDbContext.cs:1082), and the startup database-initialization path (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:70).
Snapshot
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/EntityDataSourceRegistry.cs:25· Level 2 · record (sealed, private nested)
- What it is: the immutable point-in-time view of
EntityDataSourceRegistry's state, with three members:FrozenDictionary<string, (DataSourceKey Key, Type ConfigurationType)> Entities,FrozenSet<Assembly> ScannedAssemblies, and the precomputedIReadOnlyCollection<DataSourceKey> PhysicalSources(EntityDataSourceRegistry.cs:25-28). - Depends on:
DataSourceKey;System.Collections.FrozenandSystem.Reflection.Assembly(BCL). - Concept introduced, the lock-free volatile-snapshot pattern.
[Rubric §12, Performance & Scalability]assesses whether hot-path reads avoid contention. The registry holdsprivate volatile Snapshot? _snapshot(EntityDataSourceRegistry.cs:31) and reads it without a lock, relying onvolatilefor the store/load barrier so every thread sees a fully-published reference. Writes (the initial build and any rescan) takeLock _rebuildLock(EntityDataSourceRegistry.cs:30) for mutual exclusion and then swap in a brand-newSnapshot. BecauseFrozenDictionaryandFrozenSetcannot change once built, any number of readers share one snapshot with zero synchronization, and a rescan never mutates the instance a reader is holding. - Walkthrough
Entitiesmaps an entity's full CLR type name to a tuple of the resolvedDataSourceKeyand the configuration type that produced it (EntityDataSourceRegistry.cs:26). The configuration type plays no part in routing; it exists so the duplicate-registration failure can name both conflicting configuration classes in its message (EntityDataSourceRegistry.cs:132-135).ScannedAssembliesrecords which assemblies the snapshot covered, so the registry can tell a genuine lookup miss from a merely stale scan (EntityDataSourceRegistry.cs:104).PhysicalSourcesis the distinct-key list computed once at build time (EntityDataSourceRegistry.cs:147). The remark onGetPhysicalSourcesInUseexplains why it is materialized rather than projected per call (EntityDataSourceRegistry.cs:74-80): the outbox processor and the outbox cleanup service both ask for it on every poll cycle, and re-runningSelect().Distinct()over every registered entity allocated a fresh list each time, forever, on a loop that usually finds nothing to do.
- Where it's used: exclusively inside
EntityDataSourceRegistry: built byBuildSnapshot(EntityDataSourceRegistry.cs:144-147), published byGetOrBuildSnapshot(EntityDataSourceRegistry.cs:94) and replaced byRescanIfAssembliesChanged(EntityDataSourceRegistry.cs:109-111). - Caveats / not-in-source: a private nested type. It appears in this inventory because private nested types are inventoried, but it is not part of the public API and nothing outside the registry can name it.
TenantDataSourceTarget
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:15· Level 2 · record struct (readonly)
- What it is: one unit of work for a background sweep, a
(DataSourceKey Source, string? TenantId)pair.TenantIdis null for the shared database and set when the target is a tenant that keeps its own copy of that source (TenantDataSourceTargets.cs:8-15). - Depends on:
DataSourceKey. - Concept introduced, the sweep unit under database-per-tenant.
[Rubric §8, Data Architecture]assesses whether the storage topology is modelled explicitly rather than assumed, and[Rubric §29, Resilience & Business Continuity]assesses whether background work reaches every store it is responsible for. Once multi-tenancy (ADR-073) is in play, "the databases this host owns" is no longer the same set as "the units a background job must visit": a physical source can exist once as the shared database and again as one private database per tenant that overrides it. Making that pair a value type means the sweep loops over a flat list instead of nesting a tenant loop inside a source loop, andreadonly record structgives structural equality for free, which is what the tests assert against (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Tenancy/TenantDataSourceTargetTests.cs:30-32). - Walkthrough
- The positional declaration
TenantDataSourceTarget(DataSourceKey Source, string? TenantId)(TenantDataSourceTargets.cs:15); the null-versus-set convention onTenantIdis the whole vocabulary of the type (TenantDataSourceTargets.cs:13-14). ToString()(TenantDataSourceTargets.cs:19-22) renders the bare source name for a shared target and appends" (tenant {TenantId})"for a per-tenant one, so a log line says which of two visits to the same source it is describing. That rendering is pinned by a test (TenantDataSourceTargetTests.cs:93-94), which is a small[Rubric §13, Observability & Operability]point: without it, two consecutive log lines for the same source would be indistinguishable.
- The positional declaration
- Why it's built this way: consumers branch on
TenantIdto decide whether they need a fresh DI scope. A null target runs on the caller's own scope; a non-null one creates a scope, callsITenantContext.SetTenant(...)before asking for the context, because the tenant is what routes the scoped factory to that tenant's connection string. Every sweep now gets that branch for free throughTenantDataSourceTargets.CreateTenantScope(OutboxCleanupService.cs:128,AuditTrailCleanupJob.cs:94). - Where it's used: produced by
TenantDataSourceTargets.Expand(viaExpandRelational) and consumed as the loop variable of every host-owned sweep:OutboxProcessor(OutboxProcessor.cs:163, iterated atOutboxProcessor.cs:173),OutboxCleanupService(OutboxCleanupService.cs:251-252),AuditTrailCleanupJob(AuditTrailCleanupJob.cs:75, and as a parameter atAuditTrailCleanupJob.cs:84andAuditTrailCleanupJob.cs:105), and the startup initializer (DatabaseInitializationExtensions.cs:211-212).
PhysicalDataSource
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/PhysicalDataSource.cs:21· Level 11 · record (sealed)
- What it is: the fully-resolved connection information for one physical database. Four positional
members,
Key(its engine plus name identity),ConnectionString,MigrationsAssembly?andCosmosDatabaseName(PhysicalDataSource.cs:21-25), plus two computed properties:UsesMigrations(PhysicalDataSource.cs:42-48) andIsMigrationTarget(PhysicalDataSource.cs:57-60). - Depends on:
DataSourceKeyand, through it,DataSource;DataSourceEngines, looked up byKey.Engine, whoseDataSourceEngineCapabilitiessupply theMigrationPolicyand theConnectionStringRequiredflag that both computed properties read (PhysicalDataSource.cs:42,PhysicalDataSource.cs:59). - Concept, a logical name resolved into a real connection.
[Rubric §8, Data Architecture]covers the step from a configured name likeDataSources:Conferenceto an actual database. The record's doc comment (PhysicalDataSource.cs:6-10) explains that it is produced byIDataSourceResolverfrom the top-levelConnectionStringssection (theDefaultsource) plus the namedDataSourcesentries.MigrationsAssemblyis read from the configuration key of the source's own engine,SQLServerMigrationsAssembly,SqliteMigrationsAssembly, orPostgreSQLMigrationsAssembly, and is always null for Cosmos, which migrates nothing (PhysicalDataSource.cs:13-18);CosmosDatabaseNameis ignored for relational engines (PhysicalDataSource.cs:20). A physical source belongs to exactly one engine, so one slot is enough, and the resolver never hands one engine's assembly to another. Being a positionalrecordbuys two things at once here: value equality, so two resolutions of the same source compare equal, and non-destructive mutation, which is exactly how per-tenant routing is implemented. - Walkthrough
Keyis the identity the rest of the stack routes on, and it is deliberately not recomputed when the connection changes.DbContextFactory.ResolveTenantOverrideclones the shared source withshared with { ConnectionString = ..., CosmosDatabaseName = ... }and keeps the original key, because the key is what EF's model cache is keyed on, so swapping only the connection string is what lets one compiled model serve every tenant's database (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:171-196, ADR-073).ConnectionStringmay legitimately be empty. Both the startup initializer andEnsureCreatedAsynctreat an empty connection string as "this source is not configured in this host" and skip it rather than failing (DatabaseInitializationExtensions.cs:94,DbContextFactory.cs:249-250).MigrationsAssemblyis a single positional parameter rather than three engine-scoped record-body properties, because at most one is ever populated:BuildPhysicalSourceonDataSourceResolveralready reads it from the right engine's setting, and passes null for an engine whose migration policy isNever(DataSourceResolver.cs:462-472).UsesMigrations(PhysicalDataSource.cs:42-48) is the switch that decidesMigrateversusEnsureCreatedfor this one database. It names no engine: it switches on theMigrationPolicythat the engine's descriptor declares in its capabilities,DataSourceEngines.For(Key.Engine).Capabilities.Migrations(PhysicalDataSource.cs:42).Alwaysmigrates unconditionally (PhysicalDataSource.cs:44), which is SQL Server, including the single-database monolith whoseDefaultsource names no migrations assembly at all and lets EF look next to the context.WhenAssemblyConfiguredmigrates only onceMigrationsAssemblyis set (PhysicalDataSource.cs:45), which is the rule PostgreSQL and SQLite share: neither ships with a host that already depends on being migrated, and a SQLite source wired by hand before that setting existed has no migrations to apply and must keep being created outright.Neveris Cosmos, whose provider has no migrations pipeline (PhysicalDataSource.cs:46), and an unrecognized policy falls tofalse(PhysicalDataSource.cs:47). The per-engine reasoning is kept in the property's doc comment (PhysicalDataSource.cs:27-41). All branches are pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/PhysicalDataSourceTests.cs:21,PhysicalDataSourceTests.cs:33,PhysicalDataSourceTests.cs:49,PhysicalDataSourceTests.cs:64,PhysicalDataSourceTests.cs:78, andPhysicalDataSourceTests.cs:90.IsMigrationTarget(PhysicalDataSource.cs:57-60) narrowsUsesMigrationsto the sources startup actually migrates (or, under theNonestrategy, checks): a source that uses migrations and either belongs to an engine whose capabilities setConnectionStringRequiredor has a non-empty connection string. The doc comment (PhysicalDataSource.cs:50-56) names the consequence: only SQL Server stays a target with an empty connection string, so that misconfiguration fails loudly at startup instead of being skipped, while an optional SQLite source a host leaves unconfigured stays silently absent. One rule, shared by the context factory'sGetMigrationTargets(DbContextFactory.cs:844-850) and the startup pending-migrations check (DatabaseInitializationExtensions.cs:373).
- Where it's used: produced by
DataSourceResolverthroughBuildPhysicalSource(DataSourceResolver.cs:462-472) for both the Default source (DataSourceResolver.cs:384-389) and named ones (DataSourceResolver.cs:429-434), and handed back byGetPhysical(DataSourceResolver.cs:203-208); consumed byPhysicalDbContextFactory, whoseCreate(DataSourceKey)resolves it and whoseCreate(DataSourceKey, PhysicalDataSource)overload accepts an already-resolved one, which is the entry point the tenant clone uses (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/PhysicalDbContextFactory.cs:25-28).DesignTimeDbContextHelperresolves one fordotnet efcommands and hands the same record to the design-time context (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:158), and the startup initializer branches onConnectionString,UsesMigrationsandIsMigrationTarget(DatabaseInitializationExtensions.cs:94,DatabaseInitializationExtensions.cs:99,DatabaseInitializationExtensions.cs:229,DatabaseInitializationExtensions.cs:373).
DataSourceService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceService.cs:12· Level 12 · class (public sealed)
- What it is: the Application-facing facade over
IEntityDataSourceRegistry. It answers two questions: which physical data source (engine plus database) does this entity live in, and can these two entities be joined with an EFInclude(DataSourceService.cs:6-12). - Depends on:
IEntityDataSourceRegistryas its single primary-constructor parameter (DataSourceService.cs:12),IDataSourceServiceas the contract it implements, theDataSourceKeyandDataSourcetypes it returns, andDataSourceEnginesfor the engine capability the include rule reads (DataSourceService.cs:32). - Concept introduced, routing as a first-class query.
[Rubric §7, Microservices Readiness]assesses whether "where does this entity actually live" is answerable at runtime rather than being baked into code, and[Rubric §3, Clean Architecture]assesses whether the Application layer can ask that question without referencing EF. Database-per-service (ADR-006) means two entities written in the same module's code may or may not share a physical database depending on how the deployment is configured. Every consumer that needs to make a decision about that (whichDbContextto open, whether a navigation can be eager-loaded or must go through a populator) asks this service. The class doc records an important property of the current design (DataSourceService.cs:9-10): the registry is built eagerly from configuration assemblies, so resolution no longer depends on an EF model having been built first, which is what makes it safe to consult from the Application layer at any point in startup. - Walkthrough
- The four resolution members (
DataSourceService.cs:15-24) are pure forwarders to the registry, in two pairs:GetDataSourceKeybyTypeand by full type name, andGetDataSourceby the same two, each projecting.Engineoff the resolved key. The name-based overloads exist because a caller holding only a metadata string (an EF entity type name, a message payload's type name) should not have to resolve aTypefirst. HaveIncludeSupport(first, second)(DataSourceService.cs:31-32) is the whole classification rule in one expression: the two keys must be equal and the engine's descriptor must declare itself relational,DataSourceEngines.For(first.Engine).Capabilities.IsRelational. The rule names no engine; Cosmos fails it because its capabilities say it is not relational. The remarks at:27-30state both halves: EFIncluderequires both entities in the same physical database on a relational engine, and Cosmos has no cross-document include.HaveIncludeSupport(firstEntityFullName, secondEntityFullName)(DataSourceService.cs:35-38) is the name-based overload, and it usesTryGetDataSourceKeyrather than the throwing form: an entity the registry does not know about yieldsfalse, which degrades to "use the populator path" rather than to an exception during navigation classification.
- The four resolution members (
- Why it's built this way: putting the include decision here rather than inside a repository is what lets
NavigationMetadataProviderclassify each navigation once and route it to either an EFIncludeor anINavigationPopulator(ADR-002) without knowing anything about deployment topology. Reading the relational flag off the engine descriptor keeps the same code correct on a non-relational store (ADR-018, ADR-130). It is registered as a singleton (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:62), which is safe because both the service and the registry behind it are immutable after construction. - Where it's used:
UnitOfWorkresolves an entity's key before choosing a context (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:13, doc at:29);NavigationMetadataProvideruses it for navigation classification (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:20); in MMCA.Store,InventoryAllocationService(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Infrastructure/Inventory/InventoryAllocationService.cs:35) andProductImageStorageService(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Infrastructure/Services/ProductImageStorageService.cs:28) both resolve a key before opening the right context. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/DataSourceServiceTests.csand.../DataSourceServiceAdditionalTests.cs.
IDataSourceResolver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/IDataSourceResolver.cs:15· Level 9 · interface
- What it is: the contract that maps a logical data source name (from a
[UseDatabase]attribute, a module namespace, or a setting such asOutbox:DatabaseName) to a physicalDataSourceKey, and hands back the resolvedPhysicalDataSourcefor such a key. Two members:ResolveLogical(DataSource engine, string logicalName)(IDataSourceResolver.cs:34) andGetPhysical(DataSourceKey key)(IDataSourceResolver.cs:42). - Depends on:
DataSource,DataSourceKey,PhysicalDataSource. - Concept introduced, logical-to-physical collapse as the backward-compatibility guarantee.
[Rubric §8, Data Architecture]and[Rubric §7, Microservices Readiness]both apply, because routing is reconfigurable purely through settings. The interface comment (IDataSourceResolver.cs:5-14) states the collapse rule precisely: in a host with noDataSourcesconfiguration every logical name resolves toDefault, yielding one DbContext per engine with an identical change tracker, FK constraints, transactions, and EF model to a plain single-database monolith.ResolveLogical's contract (IDataSourceResolver.cs:17-30) spells out the collapse cases: a name with noDataSourcesentry, a name with no connection string for the engine, and a name whose connection equals the top-level one all fall toDataSourceKey.Default(engine); entries sharing a connection with each other collapse to one physical source named after the alphabetically-first logical name. - Concept introduced, engine substitution. The second paragraph of the same contract
(
IDataSourceResolver.cs:24-29) adds a rule that is easy to miss and load-bearing for single-engine hosts: a request naming an engine the host configures no connection string for anywhere, neither top-level nor on a named entry, is served from an engine it does configure, preferring SQL Server, then PostgreSQL, then SQLite, then Cosmos DB. That is what lets a single-engine host (SQLite-only or PostgreSQL-only) serve the framework's own tables, whose engine settings all default to SQL Server. A host that configures the requested engine, including a polyglot host configuring several (ADR-018), is never redirected.GetPhysical(IDataSourceResolver.cs:36-42) is the reverse lookup and is documented to throw when handed a key that did not come fromResolveLogical. - Why it's built this way: the collapse is what makes "build the monolith now, extract a service
later" a configuration change rather than a rewrite
(ADR-006). One interface owns the
rule, so no caller reimplements the defaulting logic and no caller can disagree about what
Defaultmeans. - Where it's used: implemented by
DataSourceResolverand registered as a singleton (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:93); injected intoEntityDataSourceRegistry(EntityDataSourceRegistry.cs:23) to resolve each entity's derived logical name, intoPhysicalDbContextFactoryandDbContextFactoryto open connections (PhysicalDbContextFactory.cs:21,DbContextFactory.cs:52), into the inbox store and both event buses so each can locate its own database (EfInboxStoreMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Inbox/EfInboxStore.cs:35,InProcessEventBusMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:54,BrokerEventBusMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerEventBus.cs:35), intoAuditTrailReader(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailReader.cs:36) andScheduledJobRunner(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Scheduling/ScheduledJobRunner.cs:44), and optionally intoTenancySettingsValidator, which usesResolveLogicalto check that a tenant override is keyed by a name that actually round-trips as a physical source (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:25,TenancySettingsValidator.cs:147).
DataSourceResolver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceResolver.cs:16· Level 10 · class (sealed, partial)
- What it is: the singleton implementation of
IDataSourceResolver. It builds the logical-to-physical map once at construction from the connection-string settings and the namedDataSourcesentries, validates migrations-assembly conflicts, works out which engine to substitute for engines the host does not configure, and then serves both lookups from in-memory dictionaries. Every engine-specific question it asks (connection string, migrations assembly, setting name, migration policy, connection identity, substitution priority) is a lookup on the engine's descriptor throughDataSourceEngines, so the class itself switches on no engine. - Depends on:
DataSource,DataSourceKey,PhysicalDataSource,IDataSourceResolver, its own nestedDefaultSeed,ConnectionStringSettings(taken asIOptions<T>),DataSourcesSettingsandDataSourceEntrySettings;DataSourceEngines,IDataSourceEngineandMigrationPolicyfor every per-engine answer;ILogger<T>and the[LoggerMessage]source generator, which is why the class ispartial. - Concept introduced, eager and validated data-source resolution.
[Rubric §8, Data Architecture](deliberate multi-database routing) and[Rubric §7, Microservices Readiness](ADR-006, database-per-service). The resolver realizes the collapse rule described onIDataSourceResolver. Two guardrails are worth calling out. First, conflicting migrations-assembly declarations on logical names that collapse to the same physical database throw at construction (DataSourceResolver.cs:497-504), a loud fail-fast rather than a silent pick. Second,[Rubric §13, Observability & Operability]shows up in the two source-generated log methods:LogMigrationsAssemblyFallback(DataSourceResolver.cs:529-530) warns when a named source on an engine that always migrates has no dedicated migrations assembly and therefore falls back to another database's, whose snapshot describes a different schema, andLogSubstituteEngine(DataSourceResolver.cs:526-527) states at startup that requests for an unconfigured engine are being served from another one. - Walkthrough
- State (
DataSourceResolver.cs:18-52):FrameworkDefaultEngineisDataSource.SQLServer, the engine every framework-owned table asks for by default, documented as a policy constant rather than an engine capability (DataSourceResolver.cs:18-23).EnginePreferenceis the substitution order, built by orderingDataSourceEngines.Allby each engine'sSubstitutionPriority, lowest first (DataSourceResolver.cs:35-36); its doc comment records the intended order, relational first because every table the framework owns is relational, SQL Server ahead of the others, and PostgreSQL ahead of SQLite because a host that configures a server engine means it to serve the framework's own tables (DataSourceResolver.cs:25-34). The lookups are_logicalToPhysical, keyed by(engine, logical name)(DataSourceResolver.cs:39), and_physicalSources, keyed byDataSourceKey(DataSourceResolver.cs:42)._configuredEngines(DataSourceResolver.cs:45) and_substituteEngine(DataSourceResolver.cs:52) carry the substitution decision. - Constructor (
DataSourceResolver.cs:65-90): null-guards its two settings arguments (DataSourceResolver.cs:70-71), then callsBuildEngineMapfor every engine registered inDataSourceEngines.All(DataSourceResolver.cs:75-78). It then computes the configured engines and the substitute through the two static helpersConfiguredEnginesandPickSubstituteEngine(DataSourceResolver.cs:80-81), and logs once when the substitute is notFrameworkDefaultEngine(DataSourceResolver.cs:83-89). Every field is written only here, which is what makes the singleton safe to share without locking. ResolveLogical(DataSourceResolver.cs:93-107): substitutes the engine first (DataSourceResolver.cs:97), then short-circuits theDefaultname case-insensitively (DataSourceResolver.cs:99-102), then does a dictionary lookup whose miss returnsDataSourceKey.Default(effectiveEngine)(DataSourceResolver.cs:104-106), which is the monolith default.SubstituteUnconfiguredEngine(DataSourceResolver.cs:128-129) is one line, and its doc comment (DataSourceResolver.cs:109-125) carries the failure it removes: every engine choice the framework makes for its own tables comes from a setting defaulting to SQL Server (Outbox:DataSource,Scheduler:DataSource,AuditTrail:DataSource), and honoring that literally in a SQLite-only host handed those components a source with an empty connection string, so their first query failed with "The ConnectionString property has not been initialized".ResolveFrameworkDefaultEngine(DataSourceResolver.cs:140-151) is aninternal staticanswer to the same question without building a resolver: the engineResolveLogical(SQLServer, "Default")would land on, which isFrameworkDefaultEnginewhen it is configured, otherwise the substitute, andFrameworkDefaultEngineagain when nothing is configured (DataSourceResolver.cs:147-150). Registration code reads it to decide which services the default engine can back, raw SQL being registered only where that engine is relational (DataSourceResolver.cs:131-136,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:505-510). It sharesConfiguredEngines(DataSourceResolver.cs:173-179) andPickSubstituteEngine(DataSourceResolver.cs:185-189) with the constructor, so the two paths cannot disagree.HasAnyConnectionString(DataSourceResolver.cs:195-200) is what decides "configured", and it deliberately looks at named entries as well as the top-level section.ResolveConfiguredEngines(DataSourceResolver.cs:161-170) is the secondinternal staticread of configuration without a resolver: it lists the engines that carry at least one connection string, reusing the sameConfiguredEngineshelper, and orders them by registration order inDataSourceEngines.Allrather than by substitution preference (DataSourceResolver.cs:168-169). An empty list means the host configures no database at all. Its doc comment states the consumer (DataSourceResolver.cs:153-157): the startup configuration summary, which names the engines in its one Information line and so learns only WHETHER a connection string is set, never its text (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/StartupConfigurationSummaryService.cs:61-62, printingnonefor an empty list).GetPhysical(DataSourceResolver.cs:203-208): a_physicalSourceslookup that throws with an actionable message when the key was not produced byResolveLogical.BuildEngineMap(DataSourceResolver.cs:215-229): computes theDefaultSeed(DataSourceResolver.cs:221), splits the engine's named entries withClassifyEntries(DataSourceResolver.cs:222), then registers the Default source and one named source per group (DataSourceResolver.cs:223-228).ClassifyEntries(DataSourceResolver.cs:318-359): computes a per-connection identity string viaGetIdentity(DataSourceResolver.cs:515-518), which appends the database name only for an engine whose descriptor setsConnectionIdentityIncludesDatabaseName(Cosmos, where one account hosts many databases) and otherwise uses the connection string alone; the comparison is ordinal, so semantically-equal-but-textually-different connection strings deliberately do not collapse. Entries with no connection string for the engine are skipped entirely (DataSourceResolver.cs:331-336), becauseResolveLogicalalready defaults on a map miss; entries matching the seed's identity go to the collapsed list (DataSourceResolver.cs:343-347) and the rest are grouped by identity (DataSourceResolver.cs:349-356).RegisterDefaultSource(DataSourceResolver.cs:365-395): registers theDefaultkey for the engine, letting entries that collapsed onto it contribute an explicit migrations assembly alongside the seed's own (DataSourceResolver.cs:372-382), and maps each collapsed logical name onto that key (DataSourceResolver.cs:391-394).RegisterNamedSource(DataSourceResolver.cs:401-440): names the physical key after the alphabetically-first member (Order(...).First(),DataSourceResolver.cs:407) so routing is deterministic regardless of configuration key order, then, for an engine whose migration policy isAlways(SQL Server), warns and falls back to the seed's assembly when the source declares none of its own (DataSourceResolver.cs:414-422). The group's Cosmos database name comes from the canonical entry, falling back to the seed (DataSourceResolver.cs:424-427).BuildPhysicalSource(DataSourceResolver.cs:462-472): the migrations assembly was already read from the configuration key of this source's own engine viaGetMigrationsAssembly, so building the record is a straight positional construction with the assembly passed through, null only for an engine whose policy isMigrationPolicy.Never(DataSourceResolver.cs:471); which is what stops a SQL Server assembly from being handed toUseSqliteorUseNpgsql.ResolveMigrationsAssembly(DataSourceResolver.cs:485-507): returns null for aNeverengine and when no explicit value exists (DataSourceResolver.cs:490-494), and throws when logical names sharing a database declare conflicting assemblies, naming the engine's ownMigrationsAssemblySettingNameand every declaration in the message (DataSourceResolver.cs:496-504).GetMigrationsAssembly(DataSourceResolver.cs:478-479),TopLevelMigrationsAssembly(DataSourceResolver.cs:307-308) and the twoGetConnectionStringoverloads (DataSourceResolver.cs:520-524) are one-line delegations to the engine descriptor. The top-level one, used insideResolveDefaultSeed, keeps each engine on its own value: only SQL Server and PostgreSQL declare a top-level migrations assembly, so a mixed-engine host can never scaffold one engine's schema from another's snapshot (DataSourceResolver.cs:299-303).
- State (
- Why it's built this way: resolving eagerly at construction turns a misconfiguration into a startup
failure rather than a mid-request surprise, and the deterministic canonical-name rule keeps routing
stable across configuration orderings
(ADR-006). The ordinal identity
comparison is the conservative choice: collapsing two connection strings that only look different
would silently merge two databases. Engine substitution is scoped the same conservative way, since it
can only fire for a request that could not have been served at all
(
DataSourceResolver.cs:121-124). Pushing every per-engine answer onto the engine descriptor means a new engine is a new descriptor, not a new arm in each switch here (ADR-130). - Where it's used: registered as the singleton
IDataSourceResolver(DependencyInjection.cs:93), with its staticResolveFrameworkDefaultEngineread during registration (DependencyInjection.cs:505) and its staticResolveConfiguredEnginesread by the startup configuration summary (StartupConfigurationSummaryService.cs:61); consumed byEntityDataSourceRegistry, the context factories, andDesignTimeDbContextHelper, which constructs its own instance fordotnet efcommands and registers it in a hand-built container (DesignTimeDbContextHelper.cs:149-152,DesignTimeDbContextHelper.cs:218). Its rules are pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/DataSourceResolverTests.cs:12, including the alphabetically-first canonical name (DataSourceResolverTests.cs:84), the two Cosmos cases where the same account with a different database stays distinct while the same database collapses (DataSourceResolverTests.cs:99,DataSourceResolverTests.cs:118), the SQLite-only host being served the framework's SQL Server default from SQLite (DataSourceResolverTests.cs:335), the SQL-Server-only host being unchanged (DataSourceResolverTests.cs:413), the polyglot host routing each engine to itself (DataSourceResolverTests.cs:424), the host with no database at all passing the engine straight through (DataSourceResolverTests.cs:479), and PostgreSQL being preferred over SQLite as the substitute (DataSourceResolverTests.cs:578).
EntityDataSourceRegistry
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/EntityDataSourceRegistry.cs:21· Level 10 · class (sealed)
- What it is: the singleton implementation of
IEntityDataSourceRegistry. It reflects over the configuration assemblies, finds every entity type configuration, derives each entity's physical database from the configuration class's attributes and the entity's namespace, and freezes the result into a lock-free lookup that it rescans lazily when new assemblies appear. - Depends on:
DataSourceKey,IEntityDataSourceRegistry,IDataSourceResolver,IEntityTypeConfigurationBase<TEntity, TIdentifierType>,NamespaceConventions,UseDataSourceAttribute,UseDatabaseAttribute,IEntityConfigurationAssemblyProvider, and its own nestedSnapshot;System.Reflection,System.Collections.Frozen, andSystem.Threading.Lock(BCL). - Concept introduced, deriving routing from configuration classes rather than from the EF model.
[Rubric §8, Data Architecture](ADR-006: an entity lives in exactly one database) and[Rubric §15, Best Practices & Code Quality](fail fast on an ambiguous configuration). The doc comment (EntityDataSourceRegistry.cs:8-19) states the design: the map is derived from configuration classes, so it exists before any model is built; it is built lazily on first access and rescanned once on a lookup miss to pick up module assemblies loaded later; and duplicate registrations of one entity are tolerated when they agree on the physical source and rejected when they conflict. - Walkthrough
- Primary constructor (
EntityDataSourceRegistry.cs:21-23) takes theIEntityConfigurationAssemblyProviderthat decides which assemblies are scanned and theIDataSourceResolverthat performs the final collapse._rebuildLock(EntityDataSourceRegistry.cs:30) and thevolatile _snapshot(EntityDataSourceRegistry.cs:31) implement the pattern taught underSnapshot. GetDataSourceKey(Type)(EntityDataSourceRegistry.cs:34-38) null-guards and forwards to the string overload viaFullName;GetDataSourceKey(string)(EntityDataSourceRegistry.cs:41-47) isTryGetDataSourceKeyplus a throw whose message names the exact remedy, adding anEntityTypeConfigurationSQLServer/PostgreSQL/Cosmos/Sqlitefor the entity in a discovered configuration assembly.TryGetDataSourceKey(EntityDataSourceRegistry.cs:50-72): probes the current snapshot; on a miss it callsRescanIfAssembliesChangedonce (EntityDataSourceRegistry.cs:63) and retries, then returnsdefaultand false. The two-step shape keeps the common hit path entirely off the lock.GetPhysicalSourcesInUse(EntityDataSourceRegistry.cs:81-82): returns the snapshot's precomputedPhysicalSources, which is how migrations,EnsureCreated, and outbox draining enumerate this host's databases without allocating per call.GetOrBuildSnapshot(EntityDataSourceRegistry.cs:84-96) reads the volatile field first and only takes the lock when it is null;RescanIfAssembliesChanged(EntityDataSourceRegistry.cs:98-113) rebuilds only when the provider reports assemblies not already inScannedAssemblies(EntityDataSourceRegistry.cs:103-107), so a genuinely unknown entity costs one set comparison, not one rescan per lookup.BuildSnapshot(EntityDataSourceRegistry.cs:115-148): walks every (configuration, entity) pair thatEnumerateEntityConfigurationsyields for the distinct configuration assemblies (EntityDataSourceRegistry.cs:117-120) and callsDeriveDataSourceKeyfor each (EntityDataSourceRegistry.cs:122), skipping a null result. A second configuration registering the same entity against a different key throws with a message naming both configuration classes and both keys (EntityDataSourceRegistry.cs:128-136); an agreeing duplicate is simply ignored (EntityDataSourceRegistry.cs:138). The frozen dictionary, the scanned-assembly set, and the distinct physical-source list are built together at the end (EntityDataSourceRegistry.cs:144-147).DeriveDataSourceKey(EntityDataSourceRegistry.cs:159-172): reads the engine fromUseDataSourceAttributeand returns null when it is absent (EntityDataSourceRegistry.cs:161-165), deliberately skipping configurations that implement a provider interface directly instead of deriving from the attributed base classes. It then resolves the logical name in priority order,UseDatabaseAttributefirst, thenNamespaceConventions.GetModuleName, thenDataSourceKey.DefaultName(EntityDataSourceRegistry.cs:167-169), and delegates the collapse toIDataSourceResolver.ResolveLogical(EntityDataSourceRegistry.cs:171).EnumerateEntityConfigurations(EntityDataSourceRegistry.cs:181-198): aninternal staticiterator that, for every loadable type in the given assemblies, skips abstract and open-generic types (EntityDataSourceRegistry.cs:186-189), finds the closedIEntityTypeConfigurationBase<,>interface (EntityDataSourceRegistry.cs:191-192), and yields the configuration type paired with the interface's first generic argument as the entity type (EntityDataSourceRegistry.cs:193-196). Its doc comment (EntityDataSourceRegistry.cs:174-180) names why it is shared: it is the one scan both this registry and theNavigationPopulatorStartupValidatorrun, so the two cannot disagree about which entities a host maps.GetLoadableTypes(EntityDataSourceRegistry.cs:203-213): wrapsassembly.GetTypes()and toleratesReflectionTypeLoadExceptionby keeping the types that did load, mirroring module discovery, so a partially-loaded assembly does not abort the whole scan.
- Primary constructor (
- Why it's built this way: building from configuration classes at startup rather than per query
means a missing or conflicting configuration surfaces early, which matters most in a multi-database
system where the alternative failure mode is a silent read against the wrong database. The skip for
configurations without
[UseDataSource]is documented as matching legacy behavior (EntityDataSourceRegistry.cs:155-157): those entities land in the Default model but are not routable through the unit of work, which is the same fallbackApplicationDbContextapplies when filtering configurations into a model (ApplicationDbContext.cs:1081-1096). - Where it's used: registered as the singleton
IEntityDataSourceRegistry(DependencyInjection.cs:94) and rebuilt by hand for design-time commands (DesignTimeDbContextHelper.cs:152,DesignTimeDbContextHelper.cs:219); its staticEnumerateEntityConfigurationsis also called byNavigationPopulatorStartupValidator(NavigationPopulatorStartupValidator.cs:116); consumed byCrossDataSourceDegradeConvention,DataSourceService,DbContextFactory, bothApplicationDbContextmodel passes (ApplicationDbContext.cs:613,ApplicationDbContext.cs:1082), and the outbox, audit-trail and migrations enumerations. Its behavior is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/EntityDataSourceRegistryTests.cs:15, covering the agreeing and conflicting duplicate cases (EntityDataSourceRegistryTests.cs:94,EntityDataSourceRegistryTests.cs:104), the attribute-less skip (EntityDataSourceRegistryTests.cs:121), the unknown-entity throw and probe (EntityDataSourceRegistryTests.cs:130,EntityDataSourceRegistryTests.cs:140), and the distinct source enumeration (EntityDataSourceRegistryTests.cs:149).
TenantDataSourceTargets
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:43· Level 14 · class (static)
- What it is: a static class that expands the physical data sources a background service owns into
the
TenantDataSourceTargetunits it must actually visit once database-per-tenant is configured (Expand,TenantDataSourceTargets.cs:52-83), plus a scope-creation extension (CreateTenantScope,TenantDataSourceTargets.cs:100-119). Deciding which sources to feed it is not its job: that lives onFrameworkTableTargets. - Depends on:
DataSourceKey,TenantDataSourceTarget,TenancySettingswith its nestedTenantEntrySettingsandTenantDataSourceOverrideSettings,TenancySettingsValidator.ConnectionStringForfor the per-engine connection-string lookup (TenantDataSourceTargets.cs:74), andITenantContext(group-05-cqrs-pipeline.md#itenantcontext) forCreateTenantScope. - Concept introduced, why a per-tenant database is invisible to a shared sweep.
[Rubric §8, Data Architecture]and[Rubric §29, Resilience & Business Continuity]both apply, and the class remarks (TenantDataSourceTargets.cs:29-42) carry the reasoning. A shared-schema tenant needs nothing here: its rows live in the shared database that the null-tenant target already drains, and the outbox deliberately has no tenant column precisely so that adopting tenancy never forces a migration on an existing consumer. A tenant with its own database is the opposite case: its outbox rows and its audit-trail rows sit in a database nothing else opens, so without an extra target its events would sit undelivered and its rows unpurged forever. Each such tenant therefore contributes one extra target per source it overrides, and the sweep sets the tenant on its scope before asking for the context, which is what routes that context at the tenant's connection string (ADR-073). - Walkthrough
Expand(IEnumerable<DataSourceKey> sources, TenancySettings? settings)(TenantDataSourceTargets.cs:52-54) takes a nullable settings argument, because a host that never registered tenancy passes null and must still get a usable list.- It materializes the source sequence only when it is not already a collection
(
sources as IReadOnlyCollection<DataSourceKey> ?? [.. sources],TenantDataSourceTargets.cs:56) and sizes the result list from that count (TenantDataSourceTargets.cs:57), since the common no-tenancy case produces exactly one target per source. - Pass one adds the shared target for every source,
new TenantDataSourceTarget(source, null)(TenantDataSourceTargets.cs:59-62). This is the entire result when settings are null or declare no tenants (TenantDataSourceTargets.cs:64-67), which is the ordering guarantee the callers rely on: shared targets always come first. - Pass two walks the declared tenants and, for each, every source the caller owns
(
TenantDataSourceTargets.cs:69-79). A pair is added only when the tenant declares an override keyed by that physical source name and that override carries a non-blank connection string for that source's engine (TenantDataSourceTargets.cs:73-74). Both halves of that test matter: an override for a source this host does not own adds nothing, and an override that only declares, say, a SQLite connection adds nothing for a SQL Server source. Both cases have their own test (TenantDataSourceTargetTests.cs:64,TenantDataSourceTargetTests.cs:78). CreateTenantScope(this IServiceScopeFactory, TenantDataSourceTarget)(TenantDataSourceTargets.cs:100-119) null-guards the factory, creates a scope, then withdraws any ambient origin withusing (Context.AmbientOrigin.Suppress())(TenantDataSourceTargets.cs:104-105). Inside that block, when the target'sTenantIdis set it callsITenantContext.SetTenanton the scope (TenantDataSourceTargets.cs:107-110); otherwise it resolvesITenantContextonce and discards it (TenantDataSourceTargets.cs:111-116), so a shared-target scope is created unresolved and routes to the shared source. The remarks explain why (TenantDataSourceTargets.cs:93-99): the explicit target always wins over an enclosing background hop's origin (AmbientOrigin.Current, which a scope created inside an outbox, broker or internal command delivery otherwise inherits), so a scope for another tenant does not collide with the hop's tenant. The doc comment is explicit about ordering (TenantDataSourceTargets.cs:84-92): call it before asking the scope for a context, because the tenant is what routes the scoped context factory to the tenant's connection string and is also what the query filter reads.
- Why it's built this way:
Expandis a pure function over settings, with no DI and no I/O, so every caller shares one expansion rule and each target list can be unit-tested without a database (TenantDataSourceTargetTests.cs:47). Keeping the tenant loop outside the sweeps also keeps the tenancy feature additive: a host with noTenancysection gets one shared target per source and nothing else (TenantDataSourceTargetTests.cs:26,TenantDataSourceTargetTests.cs:36).CreateTenantScopecentralizes the call-order rule between setting the tenant and asking for the context, which every sweep would otherwise have to get right on its own. - Where it's used:
Expandis called byFrameworkTableTargets, which supplies the relational source set for the framework-table sweeps (FrameworkTableTargets.cs:44,FrameworkTableTargets.cs:63), and byDatabaseInitializationExtensions, which filters the expansion down tot.TenantId is not nullbecause the shared sources were already initialized in the pass above it (DatabaseInitializationExtensions.cs:211-212).CreateTenantScopeis the per-target scope call of the startup initializer (DatabaseInitializationExtensions.cs:214),OutboxProcessor(OutboxProcessor.cs:200, and per row atOutboxProcessor.cs:683),OutboxCleanupService(OutboxCleanupService.cs:128),OutboxAdministration(OutboxAdministration.cs:380),InternalCommandProcessor(InternalCommandProcessor.cs:147),InternalCommandCleanupService(InternalCommandCleanupService.cs:118),InternalCommandAdministration(InternalCommandAdministration.cs:270) andAuditTrailCleanupJob(AuditTrailCleanupJob.cs:94). Two of the sweeps are pinned against the same expansion in tests (TenantDataSourceTargetTests.cs:100,TenantDataSourceTargetTests.cs:116). - Caveats / not-in-source: the expansion is driven purely by declared configuration. A tenant whose
database exists but is not declared under
Tenancy:Tenantsproduces no target, and nothing in this class detects that; the round-trip check that a source name is a real physical name lives inTenancySettingsValidator, not here.
FrameworkTableTargets
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:32· Level 12 · class (sealed)
- What it is: a singleton that answers one question for every sweep over the framework's own
relational tables (
OutboxMessages,InternalCommands, the audit trail): which physical databases, and which per-tenant copies of them, does this host have to visit (FrameworkTableTargets.cs:8-13). Three public members,Relational()(FrameworkTableTargets.cs:43-44),Relational(DataSource, string)(FrameworkTableTargets.cs:54-64) andNamed(DataSource, string, string?)(FrameworkTableTargets.cs:75-82), all returningIReadOnlyList<TenantDataSourceTarget>. A fourth member, theinternal staticResolveHome<TEntity>(FrameworkTableTargets.cs:105-113), answers the narrower question for an opt-in framework table with a configured home: the ONEDataSourceKeythat holds it. - Depends on: three primary-constructor parameters (
FrameworkTableTargets.cs:32-35):IEntityDataSourceRegistryfor the physical sources in use,IDataSourceResolverto resolve the caller's configured home source, and an optionalIOptions<TenancySettings>(TenancySettings). It delegates the per-tenant expansion toTenantDataSourceTargets.Expandand reads the relational flag fromDataSourceEngines. - Concept introduced, one answer for "where do the framework's tables live".
[Rubric §8, Data Architecture]and[Rubric §7, Microservices Readiness]: with database-per-service (ADR-006) every relational source has its own outbox and internal-command table, and with database-per-tenant (ADR-073) each tenant that keeps its own copy of a source has another. The class remarks (FrameworkTableTargets.cs:14-24) say why this is one class: the outbox processor, the internal-command processor, both cleanup services, both operator surfaces and the audit-trail sweep all ask the same question, so the answer is derived here once rather than from the registry, the resolver and the tenancy settings inside each of them. - Walkthrough
RelationalSourcesInUse(FrameworkTableTargets.cs:115-117, private) is the base set: every physical source the registry reports in use, filtered to engines whose capabilities declare them relational. Cosmos sources drop out because they host none of these tables (FrameworkTableTargets.cs:21-22).Relational()(FrameworkTableTargets.cs:43-44) is that set, deduplicated, then passed toTenantDataSourceTargets.Expandwith the bound tenancy settings, or null when tenancy was never registered. It is what a sweep uses when its table has no configured home of its own.Relational(homeEngine, homeDatabaseName)(FrameworkTableTargets.cs:54-64) adds one more source: the physical source the caller's own settings name as its table's home, resolved throughIDataSourceResolver.ResolveLogical(FrameworkTableTargets.cs:60), but only when that engine is relational (FrameworkTableTargets.cs:58). This is what the outbox and internal-command sweeps use: the entity registry alone would miss the publish or scheduling table when it lives in a source no registered entity happens to use.Named(homeEngine, homeDatabaseName, targetName)(FrameworkTableTargets.cs:75-82) is the same list narrowed to the one target an operator named, matched case-insensitively againstTenantDataSourceTarget.ToString(), the display form the operator surfaces report (FrameworkTableTargets.cs:79-81). A null name keeps every target; a name matching nothing returns an empty list.ResolveHome<TEntity>(registry, resolver, configuredDataSourceName)(FrameworkTableTargets.cs:105-113) takes its collaborators as arguments rather than from the instance, so a store can call it without the singleton. It returns the source the registry mapsTEntityto when an entity configuration registered it (FrameworkTableTargets.cs:109-110); otherwise it builds a key from the configured name, used verbatim, on the engine the resolver answers for the default logical source (FrameworkTableTargets.cs:111-113). The remarks (FrameworkTableTargets.cs:93-99) give the reason only the engine goes through the resolver: a host with no SQL Server connection string gets the engine it does configure rather than a context over an empty connection string. It covers refresh sessions, permission grants, passkeys, view-as grants, feature-flag overrides, machine clients and webhook subscriptions (FrameworkTableTargets.cs:85-87); tables with no configured home (the notification tables) deliberately do not use it, since a guessed name could aim a sweep at a database the table does not live in (FrameworkTableTargets.cs:96-98).
- Why it's built this way: every caller recomputes the list per call, which the remarks call cheap
and tolerant of module assemblies that finish loading after startup (
FrameworkTableTargets.cs:21-22), so the class holds no cached state and is safe as a singleton (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:98). The tenancy option is defaulted to null (FrameworkTableTargets.cs:35), so a host without tenancy visits the shared databases only (FrameworkTableTargets.cs:27-31). Testing the relational flag on the engine descriptor rather than naming Cosmos keeps the rule correct for any engine registered inDataSourceEngines(ADR-130).ResolveHomeexists so a store and the sweep over the same table cannot disagree: both call the one method, so a sweep never visits a different database than its store reads (FrameworkTableTargets.cs:90-91). - Where it's used: injected into
OutboxProcessor(OutboxProcessor.cs:66, called atOutboxProcessor.cs:161),OutboxCleanupService(OutboxCleanupService.cs:55, called atOutboxCleanupService.cs:245),InternalCommandProcessor(InternalCommandProcessor.cs:49, called atInternalCommandProcessor.cs:109),InternalCommandLaneProcessor(InternalCommandLaneProcessor.cs:56, called atInternalCommandLaneProcessor.cs:234; the webhook delivery lane hands it the singleton atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookDeliveryLane.cs:78),InternalCommandCleanupService(InternalCommandCleanupService.cs:49, called atInternalCommandCleanupService.cs:182), andAuditTrailCleanupJob(AuditTrailCleanupJob.cs:47, which uses the home-lessRelational()atAuditTrailCleanupJob.cs:72). The two operator surfaces useNamed:OutboxAdministration(OutboxAdministration.cs:42, called atOutboxAdministration.cs:366) andInternalCommandAdministration(InternalCommandAdministration.cs:38, called atInternalCommandAdministration.cs:256).ResolveHomeis called statically byEFRefreshSessionStore(EFRefreshSessionStore.cs:379) and its sweepRefreshSessionCleanupService(RefreshSessionCleanupService.cs:156),EFPermissionGrantStore(EFPermissionGrantStore.cs:206),EFPasskeyCredentialStore(EFPasskeyCredentialStore.cs:85),EFViewAsGrantStore(EFViewAsGrantStore.cs:174),EFMachineClientStore(EFMachineClientStore.cs:89),EFFeatureFlagOverrideStore(EFFeatureFlagOverrideStore.cs:141) andEFWebhookSubscriptionStore(EFWebhookSubscriptionStore.cs:107). All paths except the webhook lane's are underMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/. Tests construct it inTenantDataSourceTargetTests.cs,OutboxProcessorTests.cs,OutboxProcessorExecuteAsyncTests.cs,OutboxCleanupServiceTests.csandAuditTrailCleanupJobTests.cs, among others underMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/;ResolveHomeis pinned byDataSourceResolverTests.cs:636andDataSourceResolverTests.cs:645.
ExplicitKeyInsertGroup
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/ExplicitKeyInsertGroup.cs:12· Level 0 · record (internal sealed)
- What it is: a three-member positional record,
(string Schema, string Table, IReadOnlyList<EntityEntry> Entries)(ExplicitKeyInsertGroup.cs:12). It names one batch of pending inserts that all target the same table and all carry an explicit value for a store-generated key, which is exactly the unit an engine's explicit-key toggle operates on (ExplicitKeyInsertGroup.cs:5-8). - Depends on: EF Core's
EntityEntry(ExplicitKeyInsertGroup.cs:1), and nothing first-party. - Concept introduced, importing rows that already have ids.
[Rubric §8, Data Architecture](assesses whether persistence mechanics are deliberate): a store-generated key normally means the application never supplies the id, but an import from an external system must preserve the source's ids. SQL Server only accepts that withSET IDENTITY_INSERT <table> ON, one table at a time per session (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:326-331). Grouping the affected entries by table is what turns that constraint into a loop. - Walkthrough: no members beyond the positional ones.
SchemaandTablecome from EF model metadata, never user input, which is what makes the raw toggle statement safe to build by concatenation (seeIExplicitKeyInsertDialect). - Why it's built this way: the record is engine-neutral and lives beside the engine strategies
rather than inside
DbContextFactory, because the engine produces the groups (SQLServerDataSourceEngine.FindGroups) and the factory consumes them (ADR-130). - Where it's used: returned by
IExplicitKeyInsertDialect.FindGroups(IExplicitKeyInsertDialect.cs:21), built by the SQL Server engine (SQLServerDataSourceEngine.cs:158), and consumed byDbContextFactory.SaveExplicitKeyGroupsAsync(DbContextFactory.cs:386-440), which saves each group in its own round with the toggle on, hiding the other groups'Addedentries asUnchanged(DbContextFactory.cs:399-405) and excluding their domain events from capture throughDomainEventSaveChangesInterceptor.BeginCaptureExclusion(DbContextFactory.cs:407-415).
MigrationPolicy
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/MigrationPolicy.cs:8· Level 0 · enum (internal)
- What it is: how an engine decides whether one physical source is migrated (
Migrate) or created outright (EnsureCreated) at startup (MigrationPolicy.cs:3-7). - Depends on: nothing first-party.
- Concept: one of the plain-value capabilities that replaced engine branching; the idea is taught on
DataSourceEngineCapabilities.[Rubric §8, Data Architecture]applies: schema evolution policy is a per-engine fact, not a per-call-site decision. - Walkthrough: three members.
Never(MigrationPolicy.cs:11): no migrations pipeline (Cosmos).WhenAssemblyConfigured(:14): migrated only once a migrations assembly is configured for the source (SQLite, PostgreSQL).Always(:20): always migrated, even with no migrations assembly, and a named source with none falls back to the Default source's assembly with a warning (SQL Server,MigrationPolicy.cs:16-19). - Why it's built this way: three values, not a boolean, because SQL Server's fallback behavior is distinct from "migrate when configured".
- Where it's used:
PhysicalDataSource.UsesMigrationsswitches on it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/PhysicalDataSource.cs:42-46);DataSourceResolverreadsAlwaysfor the Default-assembly fallback andNeverto drop migrations settings (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceResolver.cs:414,471,491). Each engine declares its value in itsCapabilities(for exampleCosmosDataSourceEngine.cs:41).
RowVersionStrategy
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/RowVersionStrategy.cs:8· Level 0 · enum (internal)
- What it is: how an engine maps and maintains the
RowVersionoptimistic-concurrency token (RowVersionStrategy.cs:3-7). - Depends on: nothing first-party.
- Concept: a capability value (see
DataSourceEngineCapabilities).[Rubric §8, Data Architecture]applies: optimistic concurrency is uniform for callers while the token's mechanics differ per engine. - Walkthrough: three members.
None(RowVersionStrategy.cs:11): no token configured (Cosmos).StoreGenerated(:14): a server-generatedrowversionmapped withIsRowVersion()and never stamped (SQL Server).ClientStamped(:17): a plain concurrency token the audit interceptor stamps on every insert and update (PostgreSQL, SQLite). - Why it's built this way: only SQL Server has a native row-version column type, so the other relational engines need the application to write the token; naming the strategy keeps that split in one place instead of an engine comparison in two files.
- Where it's used: mapping in
ApplicationDbContext(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:834) and stamping inAuditSaveChangesInterceptor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/AuditSaveChangesInterceptor.cs:67).
DataSourceEngineCapabilities
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/DataSourceEngineCapabilities.cs:23· Level 1 · record (internal sealed)
- What it is: what one engine can and cannot do, as plain values a call site reads instead of naming
an engine (
DataSourceEngineCapabilities.cs:3-8). Five positional members (DataSourceEngineCapabilities.cs:23-28). - Depends on:
MigrationPolicy,RowVersionStrategy. - Concept introduced, capabilities instead of engine checks.
[Rubric §1, SOLID](assesses whether code is open for extension without edits scattered across consumers): a call site that asks "is this engine relational?" keeps working when a fifth engine is added, while one that asks "is this SQL Server?" must be found and edited.[Rubric §8, Data Architecture]applies too: engine differences are recorded as data. The doc comment states the admission rule: only facts whose values genuinely differ between engines get their own member, and everything that splits exactly along the relational / non-relational line collapses intoIsRelational(DataSourceEngineCapabilities.cs:5-7). - Walkthrough:
Migrations(:24): aMigrationPolicy.ConnectionStringRequired(:25): a source with no connection string is a startup misconfiguration rather than an optional source to skip (SQL Server only,:10-13).IsRelational(:26): the bundle of relational-only features:.Include()within one physical source, transactions, raw parameterized SQL, indexes, foreign keys with meaningful delete behavior,Any(predicate)translation, and the framework's own relational tables (outbox, inbox, internal commands, scheduled jobs) (:14-19).NullsSortFirstAscending(:27): keyset pagination depends on it (:20).RowVersion(:28): aRowVersionStrategy.
- Why it's built this way: a fitness test forbids concrete engine branching outside the engine
strategies (
MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/DataSourceBranchingFitnessTests.cs:19,69), so a capability value is the sanctioned way to differ (ADR-130). - Where it's used: exposed as
IDataSourceEngine.Capabilities(IDataSourceEngine.cs:74).IsRelationalis read by the conventions (SoftDeleteUniqueIndexConventionatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/SoftDeleteUniqueIndexConvention.cs:43,RestrictDeleteByDefaultConventionatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/RestrictDeleteByDefaultConvention.cs:66,CrossDataSourceDegradeConventionatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/CrossDataSourceDegradeConvention.cs:66), byDataSourceService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/DataSourceService.cs:32) and byDomainEventSaveChangesInterceptor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:144,274).ConnectionStringRequiredis read byPhysicalDataSource(PhysicalDataSource.cs:59), andNullsSortFirstAscendingbyEFReadRepository<TEntity, TIdentifierType>, which defaults totruewhen no engine is known (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:521,733).
IExplicitKeyInsertDialect
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/IExplicitKeyInsertDialect.cs:13· Level 1 · interface (internal)
- What it is: the engine-specific half of an explicit-key insert. Only an engine that refuses an
explicit value for a store-generated key without a session toggle has one (SQL Server, through
SET IDENTITY_INSERT); every other engine returnsnullfromIDataSourceEngine.ExplicitKeyInsertand the save runs unchanged (IExplicitKeyInsertDialect.cs:5-12). - Depends on:
ExplicitKeyInsertGroup; EF Core'sDbContext. - Concept: the strategy split taught on
IDataSourceEngineapplied to one behavior. The doc comment draws the line explicitly: the engine-neutral half (grouping rounds, hiding other tables' entries, excluding their domain events, pinning the connection) stays inDbContextFactory(IExplicitKeyInsertDialect.cs:10-11). - Walkthrough:
FindGroups(DbContext)(IExplicitKeyInsertDialect.cs:21): returns the added entries whose single-column key is store-generated on this engine and carries an explicit (non-temporary) value, oneExplicitKeyInsertGroupper table; empty when nothing needs the toggle.BuildToggleSql(schema, table, enable)(:28): the raw statement that switches explicit-key insert on or off for one table. The parameters are documented as coming from EF model metadata, never user input (:24-25).
- Why it's built this way: a nullable dialect property lets the factory express "this engine needs
no toggle" without an engine check
(ADR-130). The
toggle is session state, so the factory pins one connection for the whole save
(
DbContextFactory.cs:351-361). - Where it's used: implemented by
SQLServerDataSourceEngine, which returns itself (SQLServerDataSourceEngine.cs:19,49).DbContextFactorytakes the explicit-key path only when a caller requested it and the context's engine has a dialect (DbContextFactory.cs:295-297), then drivesFindGroupsandBuildToggleSql(DbContextFactory.cs:337,423-440). The request flag is set throughIUnitOfWork.RequestExplicitKeyInsert(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:88); the one first-party caller is ADC's Sessionize refresh (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/UseCases/RefreshFromSessionize/RefreshFromSessionizeHandler.cs:213).
CosmosDataSourceEngine
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/CosmosDataSourceEngine.cs:17· Level 8 · class (internal sealed)
- What it is: the
IDataSourceEnginestrategy for Azure Cosmos DB, the one non-relational engine. - Depends on:
CosmosDbContext,IEntityTypeConfigurationCosmos<TEntity, TIdentifierType>,NamespaceConventions,ConnectionStringSettings,DataSourceEntrySettings,TenantDataSourceOverrideSettings; EF Core Cosmos provider. - Concept: see
IDataSourceEngine. - Walkthrough:
- Descriptive facts:
EngineisDataSource.CosmosDB(CosmosDataSourceEngine.cs:24),SubstitutionPriority3, the last resort (:27), andMigrationsAssemblySettingNameisnullbecause Cosmos migrates nothing (:33-34).ConnectionIdentityIncludesDatabaseNameistrue(:37): one Cosmos account hosts many databases, so the connection string alone does not identify the physical source. Capabilities(:40-45):MigrationPolicy.Never, connection string not required, not relational, nulls sort first ascending,RowVersionStrategy.None.ExplicitKeyInsertisnull(:48).- Migrations-assembly readers return
string.Empty(:72,75);CreateDbContextbuilds aCosmosDbContextover static empty options, since all configuration happens inOnConfiguring(:19-21,78-82). ApplyKeyAndTableMapping(:92-114) first refuses an entity marked[IdValueGenerated], throwingInvalidOperationExceptionat model build (:98-105): Cosmos DB generates no keys and a client-side counter cannot be unique across instances or across a restart, so a Cosmos entity assigns its own id in its factory (aGuidkey is the usual choice). Otherwise all of a module's entities share one container named after the module (falling back to the entity name) with the entityIdas partition key (:109-112), and the id is alwaysValueGeneratedNever(:113).IncludeColumnskeeps the SQL Server annotation and is unreachable in practice, since Cosmos never maps the outbox or internal-command tables that call it (:117-122);QuoteColumnuses brackets (:126) only for a filter thatBuildSoftDeleteFilterthen discards by returningnull(:129).
- Descriptive facts:
- Why it's built this way: the Cosmos-specific mapping (container, partition key, the refusal of store-generated ids) that used to be engine branches now sits in one class (ADR-130). Failing at model build turns what would be colliding ids at run time into a startup error that names the entity.
- Where it's used: registered in
DataSourceEngines(DataSourceEngines.cs:24), allow-listed as an engine strategy byDataSourceBranchingFitnessTests.cs:27, and exercised directly byCosmosGeneratedKeyTests.cs:17,29(the throw on a generated int key, and an assigned key mapped as never generated).
DataSourceEngines
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/DataSourceEngines.cs:19· Level 11 · class (internal static)
- What it is: the one registry of database engines, keyed by the shipped
DataSourcevalue (DataSourceEngines.cs:6). - Depends on:
IDataSourceEngineand its four implementations; BCLFrozenDictionary. - Concept: the lookup half of the strategy pattern taught on
IDataSourceEngine. - Walkthrough:
Registered(DataSourceEngines.cs:22-28) is the array of the four engines in registration order (Cosmos, PostgreSQL, SQLite, SQL Server).ByEngine(:30-31) freezes it into a dictionary keyed by each engine'sEngine.All(:34) exposes the array;For(DataSource)(:40-43) returns the registered engine or throwsInvalidOperationExceptionnaming the unimplemented value. - Why it's built this way: static rather than a DI service because several consumers run where no
container is reachable (model-building conventions,
EntityTypeConfiguration.ApplyEngineConventions,SoftDeleteFilterSql,IndexBuilderExtensions), and because engines are stateless facts about a closed enum that only Common can extend (DataSourceEngines.cs:8-12). Adding a fifth engine is one new class plus one line inRegistered(:14-16). - Where it's used: substitution order is
Allsorted bySubstitutionPriorityinDataSourceResolver(DataSourceResolver.cs:36) andTenancySettingsValidator(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:30);ForbacksApplicationDbContext.Engine(ApplicationDbContext.cs:59),PhysicalDbContextFactory(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/PhysicalDbContextFactory.cs:32),EntityTypeConfiguration<TEntity, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfiguration.cs:78),SoftDeleteFilterSql(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SoftDeleteFilterSql.cs:36,71),FrameworkTableTargets(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:58,117), and infrastructure registration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:507).
IDataSourceEngine
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/IDataSourceEngine.cs:18· Level 11 · interface (internal)
- What it is: everything the framework needs to know about one database engine, so that no call
site branches on
DataSource. Implementations are stateless singletons looked up throughDataSourceEngines.For(IDataSourceEngine.cs:9-12). - Depends on:
DataSource,DataSourceEngineCapabilities,IExplicitKeyInsertDialect,ApplicationDbContext,PhysicalDataSource,IEntityConfigurationAssemblyProvider, the three settings types (ConnectionStringSettings,DataSourceEntrySettings,TenantDataSourceOverrideSettings); EF CoreEntityTypeBuilderandIndexBuilder. - Concept introduced, one strategy per engine.
[Rubric §2, Design Patterns](assesses whether patterns solve a real problem idiomatically): a Strategy keyed by an enum replacesswitchandifstatements on the engine that were spread across resolver, conventions, configuration and factory code.[Rubric §1, SOLID](open/closed): a fifth engine is one class, not edits at every branch.[Rubric §34, Architecture Governance & Documentation](assesses whether architectural rules are enforced, not just written down):DataSourceBranchingFitnessTestsfails the build on concrete engine branching outside the engine strategies, with the remedy "route engine-specific behavior through IDataSourceEngine (ADR-130)" (DataSourceBranchingFitnessTests.cs:19,69). The interface groups its members in three bands: DESCRIPTIVE facts,Capabilities(plain values) and BEHAVIOUR hooks, the few places where the engine has to act rather than answer (IDataSourceEngine.cs:13-15). - Walkthrough:
- Identity:
Engine(IDataSourceEngine.cs:21), the enum value the engine answers for. - Descriptive (
:23-69):SubstitutionPriority(:29, lower wins when the resolver substitutes a configured engine for an unconfigured one; it replaces the hand-orderedEnginePreferencearray,:25-28),EntityConfigurationInterface(:32, the open generic configuration interface whose implementations belong to this engine's model),MigrationsAssemblySettingName(:38, for error messages,nullwhen the engine migrates nothing),ConnectionIdentityIncludesDatabaseName(:44), threeGetConnectionStringoverloads for the top-level section, a namedDataSourcesentry and a tenant override (:49,54,59), and the two migrations-assembly readers (:64,69). - Capabilities (
:74): aDataSourceEngineCapabilities. - Behaviour (
:76-119):CreateDbContextbuilds the engine's sealed context over one physical source, never pooled (:83-86);ApplyKeyAndTableMapping<TEntity, TIdentifierType>is the body ofEntityTypeConfiguration.ApplyEngineConventions(:95-97);IncludeColumnsadds covering columns with the engine's provider annotation (:103);QuoteColumnandBuildSoftDeleteFilterproduce the filtered-index predicate, the latternullwhere filtered indexes are unsupported (:108,113);ExplicitKeyInsertis the optionalIExplicitKeyInsertDialect(:119).
- Identity:
- Why it's built this way: recorded in ADR-130. It does not replace the one-context-class-per-engine rule (ADR-006): each strategy creates its own sealed context.
- Where it's used: four implementations
(
CosmosDataSourceEngine,PostgreSQLDataSourceEngine,SqliteDataSourceEngine,SQLServerDataSourceEngine), all held byDataSourceEngines; see that section for the consumers.ApplicationDbContextexposes the current context's engine as aninternalEngineproperty (ApplicationDbContext.cs:59), which interceptors and the factory read.
PostgreSQLDataSourceEngine
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/PostgreSQLDataSourceEngine.cs:17· Level 11 · class (internal sealed)
- What it is: the
IDataSourceEnginestrategy for PostgreSQL (Npgsql). - Depends on:
PostgreSQLDbContext,IEntityTypeConfigurationPostgreSQL<TEntity, TIdentifierType>,NamespaceConventions, the settings types; Npgsql EF provider. - Concept: see
IDataSourceEngine. - Walkthrough:
- Descriptive facts:
EngineisDataSource.PostgreSQL(PostgreSQLDataSourceEngine.cs:24),SubstitutionPriority1 (:27), settings keyPostgreSQLMigrationsAssembly(:33), connection identity by connection string alone (:36). Capabilities(:39-44):MigrationPolicy.WhenAssemblyConfigured, connection string not required, relational, nulls do not sort first ascending,RowVersionStrategy.ClientStamped.ExplicitKeyInsertisnull(:47): PostgreSQL accepts an explicit key without a toggle.- It reads its own top-level migrations assembly (
:71-75) and creates aPostgreSQLDbContext(:85-89). ApplyKeyAndTableMapping(:92-106) is deliberately identical to SQL Server, table named after the entity in the module schema (falling back todbo), so an entity moves between the two engines by changing its configuration base class alone (:98-100).- The predicate differences: Npgsql's
IncludePropertiesannotation (:109-110), double-quoted identifiers (:113) and a"IsDeleted" = falsesoft-delete filter (:116).
- Descriptive facts:
- Why it's built this way: ADR-113 keeps the mapping shared with SQL Server; ADR-130 puts what differs in this one class.
- Where it's used: registered in
DataSourceEngines(DataSourceEngines.cs:25); allow-listed byDataSourceBranchingFitnessTests.cs:28.
SqliteDataSourceEngine
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SqliteDataSourceEngine.cs:16· Level 11 · class (internal sealed)
- What it is: the
IDataSourceEnginestrategy for SQLite. - Depends on:
SqliteDbContext,IEntityTypeConfigurationSqlite<TEntity, TIdentifierType>, the settings types; EF Core SQLite provider and the SQL Server index-builder extension. - Concept: see
IDataSourceEngine. - Walkthrough:
- Descriptive facts:
EngineisDataSource.Sqlite(SqliteDataSourceEngine.cs:23),SubstitutionPriority2 (:26), settings keySqliteMigrationsAssembly(:32), connection identity by connection string alone (:35). Capabilities(:38-43):MigrationPolicy.WhenAssemblyConfigured, connection string not required, relational, nulls sort first ascending,RowVersionStrategy.ClientStamped.ExplicitKeyInsertisnull(:46).GetTopLevelMigrationsAssemblyalways returns empty:ConnectionStringscarries no SQLite migrations assembly, so a mixed-engine host can never hand SQLite the SQL Server snapshot (:70-74). Only a namedDataSourcesentry can supply one.ApplyKeyAndTableMapping(:91-103) maps to a table named after the entity with no schema (:97) and a generated key asValueGeneratedOnAdd().UseIdentityColumn(1, 1)(:100).IncludeColumnskeeps the SQL Server annotation, which the SQLite provider ignores (:106-108); double-quoted identifiers (:112) and a"IsDeleted" = 0filter (:115).
- Descriptive facts:
- Why it's built this way: see ADR-130.
- Where it's used: registered in
DataSourceEngines(DataSourceEngines.cs:26); allow-listed byDataSourceBranchingFitnessTests.cs:30.
SQLServerDataSourceEngine
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DataSources.Engines·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:19· Level 11 · class (internal sealed)
- What it is: the
IDataSourceEnginestrategy for SQL Server, and the only engine that also implementsIExplicitKeyInsertDialect(SQLServerDataSourceEngine.cs:19). - Depends on:
SQLServerDbContext,IEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>,ExplicitKeyInsertGroup,NamespaceConventions, the settings types; EF Core SQL Server provider. - Concept: see
IDataSourceEngineand, for the explicit-key toggle,ExplicitKeyInsertGroup. - Walkthrough:
- Descriptive facts:
EngineisDataSource.SQLServer(SQLServerDataSourceEngine.cs:26),SubstitutionPriority0, the preferred substitute (:29), settings keySQLServerMigrationsAssembly(:35), connection identity by connection string alone (:38). Capabilities(:41-46):MigrationPolicy.Always, connection string required, relational, nulls sort first ascending,RowVersionStrategy.StoreGenerated.ExplicitKeyInsertreturnsthis(:49).- Reads its top-level migrations assembly (
:73-77) and creates aSQLServerDbContext(:87-91). ApplyKeyAndTableMapping(:94-107): table named after the entity in the module schema (falling back todbo), shared verbatim with PostgreSQL (:100-101).- Bracket-quoted identifiers (
:114) and a[IsDeleted] = 0filter (:117). FindGroups(:120-159) walks the change tracker forAddedentries (:128), skips anything without a single-property primary key (:132-134), keeps only keys whose SQL Server value-generation strategy isIdentityColumn(:137-141), skips entries whose key is still an EF temporary value, since only an explicitly set (imported) value needs the toggle (:143-146), and buckets survivors by(schema, table)withdboas the schema fallback (:148-155).BuildToggleSql(:162-163) concatenatesSET IDENTITY_INSERT [schema].[table] ON|OFF; the identifier cannot be parameterized, and the caller suppressesS2077with that justification (DbContextFactory.cs:422).
- Descriptive facts:
- Why it's built this way: SQL Server is the default engine, so it alone requires a connection
string and migrates even with no configured assembly (falling back to the Default source's assembly,
MigrationPolicy.cs:16-19). Implementing the dialect on the engine itself keeps the identity-insert rules (identity strategy, temporary values) next to the other SQL Server facts (ADR-130). - Where it's used: registered in
DataSourceEngines(DataSourceEngines.cs:27); allow-listed byDataSourceBranchingFitnessTests.cs:29; its dialect is driven byDbContextFactory(DbContextFactory.cs:295-297,337).
DetectChangesScope
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:506· Level 0 · struct (private readonly, nested)
- What it is: a two-field disposable struct nested inside
ApplicationDbContextwhose only job is to put EF'sChangeTracker.AutoDetectChangesEnabledflag back the way it found it when a save finishes. - Depends on:
Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTrackerandSystem.IDisposable(both external/BCL); nothing first-party beyond its enclosing context class. - Concept introduced, the scoped-setting guard (restore-on-dispose).
[Rubric §12, Performance & Scalability](assesses whether hot paths avoid repeated O(n) work) and[Rubric §15, Best Practices & Code Quality](assesses whether temporary global-state mutation is bounded rather than leaked). EF'sChangeTracker.Entries<T>()runs a fullDetectChangespass on every call and memoizes nothing. Interceptors scan the tracker duringSavingChangesand EF then detects once more on its own before building the save, so a single save paid threeO(tracked entities x properties)snapshot comparisons where one suffices (ApplicationDbContext.cs:479-486). Turning detection off for the duration of the save is the optimization; ausing-scoped struct is what makes turning it back on unforgettable, including on the exception path. - Walkthrough: the primary constructor
DetectChangesScope(ChangeTracker changeTracker, bool previousSetting)(ApplicationDbContext.cs:506) captures the tracker and the flag value that was in force before suppression.Dispose()(ApplicationDbContext.cs:508) is a single expression-bodied assignment that writespreviousSettingback ontochangeTracker.AutoDetectChangesEnabled. It is created only byDetectChangesOnce()(ApplicationDbContext.cs:496-504), which reads the current setting (:235), callsChangeTracker.DetectChanges()once when detection was on (:236-237), sets the flag tofalse(:239), and hands back the scope (:240). - Why it's built this way:
readonly structmeans no heap allocation on a path that runs on every save, andprivatekeeps the mechanism invisible to callers. Restoring the previous value rather than hardcodingtrueis the load-bearing detail: a caller that had deliberately disabled auto-detect keeps its choice and never gets an unexpected detection pass on the way out (ApplicationDbContext.cs:491-493). Suppressing the remaining passes is safe because everything the interceptors do afterwards bypasses detection anyway: the audit interceptor writes throughentry.Property(...).CurrentValue(AuditSaveChangesInterceptor.cs:80-83) and the domain-event interceptor adds outbox rows throughAdd, both of which take effect on the entry immediately. - Where it's used: both save overrides that EF funnels through,
SaveChangesAsync(bool, CancellationToken)(ApplicationDbContext.cs:229-239) andSaveChanges(bool)(ApplicationDbContext.cs:267-275), open one withusing var detection = DetectChangesOnce(). The behavior is pinned bySaveChangeDetectionTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Interceptors/SaveChangeDetectionTests.cs:31,:47,:64,:78,:90), which asserts detection runs exactly once, that an untracked property edit still persists, that audit stamps still land, that a caller's explicitfalsesurvives the save, and that a default context is left with detection enabled for the next caller. - Caveats / not-in-source: the remarks name two tracker-scanning interceptors
(
AuditSaveChangesInterceptoratAuditSaveChangesInterceptor.cs:69andDomainEventSaveChangesInterceptoratDomainEventSaveChangesInterceptor.cs:262), which are the two that are always registered. Two optional interceptors enumerate the tracker as well when a host opts into them (TenantSaveChangesInterceptoratTenantSaveChangesInterceptor.cs:86andAuditTrailSaveChangesInterceptoratAuditTrailSaveChangesInterceptor.cs:238), so the suppression saves strictly more than the comment claims; the comment is narrower than the code, not wrong about the mechanism.
ModelBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ModelBuilderExtensions.cs:10· Level 0 · class (internal static)
- What it is: an internal static class holding a single extension member,
ApplyAllConfigurations, that scans an assembly for concrete classes implementing a provider-specific configuration interface, instantiates each through DI, and applies it to the EF model, with an optional per-entity filter. - Depends on:
Microsoft.EntityFrameworkCore.ModelBuilder,System.Reflection, andMicrosoft.Extensions.DependencyInjection.ActivatorUtilities(all BCL/EF/NuGet). It is called byApplicationDbContext; it does not itself referenceNamespaceConventionsorEntityConfigurationOptions. - Concept introduced, reflection-driven configuration application with a DI-aware activator.
[Rubric §8, Data Architecture](assesses deliberate, discoverable model configuration) and[Rubric §2, Design Patterns](a generic apply-all built over EF'sApplyConfiguration<TEntity>): because the entity CLR type is only known at runtime, the method resolves EF's open genericModelBuilder.ApplyConfiguration<TEntity>(IEntityTypeConfiguration<TEntity>)once, then closes it per entity viaMakeGenericMethod. Configurations are created withActivatorUtilities.CreateInstance(ModelBuilderExtensions.cs:62), so a configuration class may constructor-inject services rather than needing a parameterless ctor. The member is declared inside a C#extension(ModelBuilder modelBuilder)block (ModelBuilderExtensions.cs:12), the preview extension-member syntax this workspace uses instead ofthis-parameter extension methods. - Walkthrough:
- Guards all four required arguments with
ArgumentNullException.ThrowIfNull(ModelBuilderExtensions.cs:31-34). - Resolves the single-parameter
ApplyConfigurationoverload by reflection (ModelBuilderExtensions.cs:38-40). - Selects concrete, non-generic-definition types in the assembly whose interface set contains a closed
form of
interfaceType(the open generic likeIEntityTypeConfigurationSQLServer<,>) (ModelBuilderExtensions.cs:42-51). - For each, takes the first generic argument as the entity type, skips it when
entityFilterreturns false (ModelBuilderExtensions.cs:56-60), then instantiates viaActivatorUtilitiesand invokes the closedApplyConfiguration(ModelBuilderExtensions.cs:62-64).
- Guards all four required arguments with
- Why it's built this way:
internalkeeps this a framework detail; modules never call it. TheentityFilterparameter is the boundary that keeps each physical database's model to only its own entities (seeApplicationDbContext), and DI-based activation lets configurations depend on services without a parameterless-ctor constraint. - Where it's used: called from
ApplicationDbContext.ApplyConfigurationsForEntitiesInContext(ApplicationDbContext.cs:1094-1100), which passes the engine's configuration interface (for exampleIEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>) and a filter that matches each entity's registry-resolvedDataSourceKey.
INpgsqlDataSourceConfigurator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/INpgsqlDataSourceConfigurator.cs:23· Level 0 · interface
- What it is: a one-method extension point,
void Configure(NpgsqlDataSourceBuilder builder)(INpgsqlDataSourceConfigurator.cs:27), that customizes theNpgsqlDataSourceeveryPostgreSQLDbContextand the PostgreSQL readiness check share for one connection string. The doc comment names what a configurator typically adds: a password provider (an RDS IAM token, a vault lease), a client certificate callback, or a type mapping (INpgsqlDataSourceConfigurator.cs:6-8). - Depends on: Npgsql's
NpgsqlDataSourceBuilderonly; nothing first-party. - Concept introduced, opt-in connection customization without touching the context.
[Rubric §8, Data Architecture](how a context reaches its database is configurable per engine) and[Rubric §11, Security](a short-lived token can replace a password stored in the connection string): EF'sUseNpgsqlaccepts either a connection string or a prebuiltNpgsqlDataSource, and only the second can carry a password provider. The interface lets an adapter package contribute that builder-level configuration while the context, the broker transport and the health check stay unaware of which cloud supplied it. The remarks state the null case as the contract: with no configurator registered nothing changes, the context hands EF the raw connection string and no data source is built (INpgsqlDataSourceConfigurator.cs:11-13). - Walkthrough:
Configure(:27): receives a builder that already carries the connection string, so a configurator can read it throughNpgsqlDataSourceBuilder.ConnectionStringBuilder(:26).- Registration:
services.AddNpgsqlDataSourceConfigurator(configurator)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Persistence.cs:24) adds the instance withTryAddEnumerable(:28), which makes it idempotent per configurator type, and registers the keyedNpgsqlDataSourcesingleton thatNpgsqlDataSourcesbacks (:32-34). Its doc comment notes the call is order-independent relative toAddInfrastructureandAddServiceDefaults, because both sides look the data source up on first use (DependencyInjection.Persistence.cs:18-20). - Lifetime: once at least one is registered, one data source is built per distinct connection
string the first time a context or the health check asks, every registered configurator runs on
its builder once, and the container disposes it (
INpgsqlDataSourceConfigurator.cs:13-15).
- Why it's built this way: the core stays cloud-neutral and the vendor detail lives in the
adapter packages
(ADR-134), while
the per-engine boundary keeps the hook PostgreSQL-only: SQL Server, SQLite and Cosmos sources never
reach a configurator (
INpgsqlDataSourceConfigurator.cs:19-20, ADR-130, ADR-113). Throwing fromConfigurefails the first context or probe for that connection string, which the remarks name as the place to reject a connection string a configurator cannot serve (:20-21). - Where it's used: implemented by
RdsIamAuthenticationConfigurator(MMCA.Common/Source/Hosting/MMCA.Common.Aws/Rds/RdsIamAuthenticationConfigurator.cs:20-21) andCloudSqlIamAuthenticationConfigurator(MMCA.Common/Source/Hosting/MMCA.Common.Gcp/CloudSql/CloudSqlIamAuthenticationConfigurator.cs:23), both of which installUsePeriodicPasswordProvider(RdsIamAuthenticationConfigurator.cs:39,CloudSqlIamAuthenticationConfigurator.cs:54). Enumerated byNpgsqlDataSources.Create; thePostgreSqlBrokerTransportruns the bus on the same shared data source when one is registered (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Transports/PostgreSql/PostgreSqlBrokerTransport.cs:34-36). Pinned byNpgsqlDataSourceConfiguratorTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/NpgsqlDataSourceConfiguratorTests.cs),AwsRdsIamAuthenticationTestsandCloudSqlIamAuthenticationTests. - Caveats / not-in-source: the broker's startup migration runs on the same shared data source, so
a broker database on IAM authentication needs no separate migration setting
(
PostgreSqlBrokerTransport.cs:34-36);MessageBus:PostgreSql:MigrateOnStartup=falseonly turns the startup schema creation off (PostgreSqlBrokerTransport.cs:27-29).
ModelContributorPhase
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ModelContributorPhase.cs:8· Level 0 · enum
- What it is: a two-value enum that says when an
IModelContributorruns insideApplicationDbContext.OnModelCreating, relative to the framework's soft-delete, tenant and concurrency passes.BeforeEntityPasses = 0(ModelContributorPhase.cs:16) andAfterEntityPasses = 1(:23). - Depends on: nothing; it is a plain enum read through
IModelContributor.Phase(IModelContributor.cs:46). - Concept introduced, ordering a contribution against the entity passes.
[Rubric §8, Data Architecture]: the base context's entity passes (ApplySoftDeleteFilters,ApplyTenantFilters,ConfigureConcurrencyTokens) act on whatever entity types are in the model at the moment they run. An optional table that is anIAuditableEntitymust therefore be in the model before them, so it gets the soft-delete filter and its concurrency token (and anITenantEntityits tenant filter); a table with no soft-delete, tenant or concurrency semantics of its own must be added after them, so no pass touches it. The phase states that choice once, on the contributor. - Walkthrough:
BeforeEntityPasses(ModelContributorPhase.cs:10-16): runs beside the module entity configurations, so the passes see the contributed types. The phase taken by the feature-flag overrides (FeatureFlagOverrideModelBuilderExtensions.cs:89), the machine clients (MachineClientModelBuilderExtensions.cs:74) and the webhook subscriptions (WebhookSubscriptionModelBuilderExtensions.cs:77), each an auditable entity.AfterEntityPasses(:18-23): runs after the entity passes and after the framework's own outbox, inbox and internal-command tables. The phase taken by the job store (ScheduledJobModelContributor.cs:22), the change trail (AuditTrailModelContributor.cs:20), refresh sessions (RefreshSessionModelBuilderExtensions.cs:143), permission grants (PermissionGrantModelBuilderExtensions.cs:87), view-as grants (ViewAsGrantModelBuilderExtensions.cs:76) and passkeys (PasskeyCredentialModelBuilderExtensions.cs:75).
- Why it's built this way: under
ADR-148
the base context does not know which optional tables exist, so the ordering fact has to travel with
each contributor, and an explicit enum keeps it a declared choice rather than an accident of
registration order. Contributors that
share a phase still run in registration order, because
OnConfiguringsorts with the stableOrderBy(ApplicationDbContext.cs:547-554). - Where it's used: read by
ApplicationDbContext.OnConfiguring, which orders the applying contributors by phase (ApplicationDbContext.cs:553), and by the privateApplyModelContributors, whichOnModelCreatingcalls once per phase (ApplicationDbContext.cs:649,:448,:457-464).
NpgsqlDataSources
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/NpgsqlDataSources.cs:19· Level 1 · class (internal static)
- What it is: the shared
NpgsqlDataSourcecache behindINpgsqlDataSourceConfigurator. It holds no state of its own: the cache is the DI container, whichAddNpgsqlDataSourceConfiguratorgives a keyed singleton underKeyedService.AnyKeywhose key is the connection string, so one instance exists per distinct connection string, every caller gets the same one, and the container disposes it (NpgsqlDataSources.cs:7-11). - Depends on:
INpgsqlDataSourceConfigurator,Microsoft.Extensions.DependencyInjectionkeyed services, and Npgsql. - Concept introduced, the container as a keyed cache.
[Rubric §8, Data Architecture](one pooled data source per physical database rather than one per context instance): keying by the connection string is what lets MMCA.Common.Aspire's PostgreSQL readiness check reach the same instance without referencing this package, since both sides name only an Npgsql type and a string (NpgsqlDataSources.cs:13-15). - Walkthrough:
Resolve(IServiceProvider, string)(:29-32): returns the keyedNpgsqlDataSourcefor the connection string, ornullwhen the provider is not anIKeyedServiceProvider(the design-time provider behinddotnet ef), the connection string is blank, or no configurator registered the keyed factory (:21-25).nullis the signal the callers branch on.Create(IServiceProvider, object?)(:42-56): the keyed-singleton factory. A key that is not a non-blank string returnsnull(:44-47), so an unrelated keyed lookup ofNpgsqlDataSourceis not answered by this one (:36-37). Otherwise it builds anNpgsqlDataSourceBuilderfor the connection string (:49), runs every registered configurator on it in registration order (:50-53), and returnsbuilder.Build()(:55).
- Why it's built this way: nothing is registered until a configurator is added, so a host without
one resolves
nulland keeps the plain connection-string path unchanged (NpgsqlDataSources.cs:15-16).internalkeeps the cache a framework detail; the public surface is the configurator interface and its registration method (ADR-113). - Where it's used:
Createis the factory passed toTryAddKeyedSingleton(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Persistence.cs:32-34);Resolveis called byPostgreSQLDbContext.OnConfiguring(PostgreSQLDbContext.cs:63) and byPostgreSqlBrokerTransport(PostgreSqlBrokerTransport.cs:119). The readiness check performs the same keyed lookup independently (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Health/PostgreSqlHealthCheck.cs:105-108).
ApplicationDbContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:44· Level 8 · class (abstract)
- What it is: the single abstract
DbContextbase that every engine-specific context (SQLServerDbContext,PostgreSQLDbContext,CosmosDbContext,SqliteDbContext) inherits. One instance exists per physical database: the same class is instantiated multiple times, each carrying a differentPhysicalDataSourceand building a model that contains only that database's entities (ApplicationDbContext.cs:44-49). - Depends on:
AuditSaveChangesInterceptor,DomainEventSaveChangesInterceptor,TenantSaveChangesInterceptor,AuditTrailSaveChangesInterceptor,DataSourceModelCacheKeyFactory,IModelContributorandModelContributorPhase,CrossDataSourceDegradeConvention,SoftDeleteUniqueIndexConvention,RestrictDeleteByDefaultConvention,IEntityDataSourceRegistry,IEntityConfigurationAssemblyProvider,PhysicalDataSource,DataSourceKey,IDataSourceEnginethroughDataSourceEngines,SoftDeleteFilterSql,SensitiveDataLoggingGate,IAuditableEntity,ITenantEntity,AuditableBaseEntity<TIdentifierType>,OutboxMessage,InboxMessage,InternalCommandMessage,TransactionCommitAmbiguousException,PersistenceSettingsviaIOptions<>, the optionalStronglyTypedIdRegistry, MiniProfiler and EF Core. - Concept introduced, DbContext as Unit of Work + Change Tracker.
[Rubric §8, Data Architecture](assesses transactions, migrations, soft-delete, audit, concurrency): EF'sDbContextis the unit of work, tracking everyAdded/Modified/Deletedentity since the last save and writing them in a single transaction. This is also[Rubric §3, Clean Architecture](the EF detail stays in Infrastructure; domain entities carry no EF attributes) and[Rubric §6, CQRS & Event-Driven](domain events are captured transactionally with the aggregate write). The interceptors registered inOnConfiguringrun aroundbase.SaveChangesAsyncto stamp audit fields, stamp and guard the tenant, serialize domain events into the outbox, and diff the change trail, so those cross-cutting concerns live in the interceptor pipeline rather than inline in every handler. - Concept introduced, named global query filters.
[Rubric §11, Security]and[Rubric §30, Compliance, Privacy & Data Governance](both assess whether isolation of other parties' data is structural rather than per-query discipline): this class declares two filters by name,SoftDelete(ApplicationDbContext.cs:712) andTenant(:715). EF composes named filters with AND, so a tenant-owned soft-deletable entity is filtered on both without either filter knowing about the other, and a caller asking to see deleted rows drops exactlySoftDeleteand leavesTenantin force (:707-711,:730-733). Isolation therefore cannot be forgotten at a call site, and the tenant filter fails closed: a scope with no resolved tenant reads no tenant-owned rows unless it was explicitly declared an all-tenants scope (:746-754). - Walkthrough:
- Primary constructor (
ApplicationDbContext.cs:44-49): takesDbContextOptions, anIServiceProvider, anIEntityConfigurationAssemblyProvider, and thePhysicalDataSourcethis instance targets, delegating toDbContext(options). DataSourceKey(:52): exposes the(engine, database name)pair this context serves;PhysicalSource(:128) exposes the resolved connection info to subclasses asinternal.Engine(:59):internal,DataSourceEngines.For(physicalDataSource.Key.Engine), theIDataSourceEnginethis context targets. Its doc comment (:54-58) names both halves of what it answers: what the engine can do (whether it hosts the framework's relational tables, so the transactional outbox, which Cosmos DB does not) and how its SQL and keys are shaped. Every engine branch in this class readsEngine.Capabilitiesrather than comparing aDataSourcevalue, and the same property is whatDomainEventSaveChangesInterceptortests (Engine.Capabilities.IsRelational,DomainEventSaveChangesInterceptor.cs:147,:277) and whatDbContextFactoryreads for transactions and explicit-key inserts.EngineAnnotation(:65): theinternal constmodel annotation name"MMCA:Engine", which carries the engine of the model being built while entity configurations are applied (seeApplyConfigurationsForEntitiesInContextbelow)._modelContributors(:83): the one private field that decides which optional tables this context's model carries. It holds theIModelContributors that apply to this context's physical source, in the orderOnModelCreatingruns them. Its remarks (:67-82) state the rule that keeps it correct:OnModelCreatingmust not depend on anything the model cache key does not cover, so the list is resolved once, up front, inOnConfiguring, the same place the interceptors are resolved. Every optional table the framework ships (stored permission grants, feature-flag overrides, view-as grants, passkeys, machine clients, webhook subscriptions, the job store, the change trail, refresh sessions) arrives this way, registered by its feature's ownAddXcall with its gate in the contributor'sAppliesTo; a host that registers none, or whose contributors all decline this source, builds exactly the base model._auditTrailRegistered(:90): a private flagOnConfiguringsets when the host registered the change trail's interceptor (AddAuditTrail,:544). It gates the key fix-up transaction described under the save overrides below: without the interceptor nothing is ever pending.ModelContributorKey(:114) andStronglyTypedIdModelKey(:125): the twointernalvaluesDataSourceModelCacheKeyFactoryadds to the model cache key.ModelContributorKeyis the applying contributors' assembly-qualified type names joined in application order (empty when none applies), memoized in the property'sfield. Its remarks (:99-113) record why types, never instance state, are enough: a contributor'sConfigureis required to depend only on its type and the engine, so every model difference a host's settings make shows up as a type joining or leaving the list, and a new optional table needs nothing here.StronglyTypedIdModelKeyis the host's declared wrapper types as one string of assembly-qualified names, or empty when noStronglyTypedIdRegistryis registered, becauseConfigureConventionsmaps every declared wrapper and so the declared set changes the model. It is keyed on content, never on the registry instance, and memoized per registry in the staticConditionalWeakTableStronglyTypedIdModelKeys(:97), so the cached key is collected with the provider that owns the registry.TenantIdAccessor(:143) andCurrentTenantId(:150): aninternal Func<string?>?assigned by the scopedDbContextFactoryat context creation (DbContextFactory.cs:152), and the public property that invokes it. The remarks (:136-142) explain why it is an accessor and not a copied value: a context can be created before the request's tenant is resolved, and a copy taken at that moment would pin the context to the wrong answer for its whole life.nullreads as "no tenant", which under theTenantfilter hides every tenant-owned row unless the scope is an all-tenants scope.AllTenantsAccessor(:159) andIsAllTenantsScope(:166): the same accessor shape for the other half of the tenant filter.AllTenantsAccessoris aninternal Func<bool>?wired by the factory beside the tenant accessor (DbContextFactory.cs:153, readingITenantContext.IsAllTenants), andIsAllTenantsScopeinvokes it, readingfalsewhen it isnull, so a context created outside a scope is never an all-tenants scope. Seeing every tenant's rows takes an explicitITenantContext.SetAllTenantson the scope (:152-158).OutboxOriginAccessor(:183) andCurrentOutboxOrigin(:189): the same accessor shape, one step wider.OutboxOriginAccessoris aninternal Func<Outbox.OutboxOrigin>?assigned by the scopedDbContextFactoryalongside the tenant accessors (DbContextFactory.cs:157) and read once per save byDomainEventSaveChangesInterceptorwhen it writes outbox rows. The remarks (:174-182) name the reason it is an accessor rather than an injected service: a context is built by the singletonPhysicalDbContextFactoryand carries only the root provider, and the interceptor that needs the ambient values is itself a singleton, so neither can reach a scoped service directly; the scoped factory is the one component that sits in both worlds.null(a context created outside a scope, design time or a directly-constructed test context) reads as "nothing captured", andCurrentOutboxOriginfalls back todefaultin that case.CurrentSaveUserId(:196):internalaudit user id with a private setter, written by the save overloads and read byAuditSaveChangesInterceptor;nullmarks a system operation and the interceptor resolves it todefault.SaveChangesAsync(userId, ct)(:206): the mutation entry point. Opens a MiniProfiler step, setsCurrentSaveUserId, callsbase.SaveChangesAsync, and clears the id again in afinallyso a later plainbase.SaveChangesAsyncon the same instance (an internal outbox write, for example) cannot silently reuse the previous caller's identity for its stamps.SaveChanges(userId)(:249): the synchronous counterpart with the same set/reset discipline. Its doc comment records the behavioral difference: the sync path cannot dispatch events in-process, so captured events are delivered by the outbox processor instead.- Save overrides (
:229,:267): both EF save overloads openusing var detection = DetectChangesOnce()(:496), the optimization taught underDetectChangesScope. Each then asksNeedsKeyFixUpTransactionand, when it answers yes, routes the save throughSaveWithKeyFixUpTransactionAsync(:235-236) or its synchronous twin (:271-272); otherwise it calls the base save unchanged. The remarks (:223-228,:263-266) name the purpose: when the change trail is on and the save inserts an audited row whose key the database assigns, the trail row's key fix-up commits with the data it describes. NeedsKeyFixUpTransaction(:286-292): private; true only when_auditTrailRegisteredis set, the engine is relational, no transaction is open (Database.CurrentTransactionand the ambientSystem.Transactions.Transaction.Currentare both null),AutoTransactionBehavioris notNever, andAuditTrailSaveChangesInterceptor.HasPendingGeneratedKeysreports an audited insert that really has a temporary key (AuditTrailSaveChangesInterceptor.cs:591). Its doc comment (:277-285) gives the reason: the fix-up is one statement AFTER the insert, so it needs a transaction to be atomic with it; an already-open one (anITransactionalcommand, an explicit transaction, or an ambientTransactionScope) is simply joined, and every other save keeps EF's own implicit transaction at no extra cost.SaveWithKeyFixUpTransactionAsync(:315-352) andSaveWithKeyFixUpTransaction(:355-389): open the transaction INSIDEDatabase.CreateExecutionStrategy()(a retrying strategy, SQL Server's included, refuses a user-initiated transaction opened outside it), save withacceptAllChangesOnSuccess: false, commit, and only then callChangeTracker.AcceptAllChanges()when the caller asked for it (:347-348), so a transient failure of the insert or the fix-up rolls the attempt back and the strategy re-runs it against changes still pending (:295-299). The commit itself is never retried:TryCommitAsyncandTryCommit(:395-411,:414-429) turn any commit failure into aTransactionCommitAmbiguousExceptionthat is carried out of the strategy and thrown after it (:344-345), because a commit's outcome is unknowable and re-running a possibly-durable insert duplicates it (:303-307). Every failure path callsAbandonKeyFixUpAttempt(:469-473), which drops the deferred in-process dispatch (DomainEventSaveChangesInterceptor.DropDeferred) and re-arms the trail's discard of its staged rows (AuditTrailSaveChangesInterceptor.MarkCaptureAbandoned,AuditTrailSaveChangesInterceptor.cs:606), so a retry, or the caller's next save, writes each trail row once (:310-312).DisposeBestEffortAsyncandDisposeBestEffort(:436-463) swallow a failed rollback so the strategy judges retriability on the save's own error. After a successful commit the async path flushes the deferred domain-event dispatch (DomainEventSaveChangesInterceptor.FlushDeferredAsync,:350); the sync path dispatches nothing in-process, so it has nothing to flush (:386-388).OnConfiguring(:512-580): resolves the two always-present interceptors from DI (:519-520) and adds them, insertingTenantSaveChangesInterceptorbetween them when it is registered (:527-534). Registration order is execution order, and the comment (:522-526) states why the tenant interceptor belongs in the middle: after the audit stamps (it must not run against half-stamped entries) and before the domain-event interceptor serializes outbox rows, so those rows describe an entity whose tenant is already final.AuditTrailSaveChangesInterceptoris appended last when present (:541-545), because it diffs the final values, and its presence sets_auditTrailRegistered(:544). Both optional interceptors are fetched withGetService, notGetRequiredService: a host that never opted in, a design-time context, or a directly constructed test context must still build. The method then resolves_modelContributors(:547-554): on a relational engine only, every registeredIModelContributorwhoseAppliesToaccepts this physical source, ordered byPhasewith the stableOrderByso contributors sharing a phase keep registration order; on Cosmos DB the list is empty, because Cosmos never runs the baseOnModelCreatingand a contributor must not split its cache key either (:547-549). It resolvesStronglyTypedIdModelKey(:556-561), callsConfigureSensitiveDataLogging(:563), downgrades EF'sRelationalEventId.MigrationsNotFoundto a log entry (:570; the comment at:565-569records that EF Core 11 raises it as an error insideMigrateAsyncwhere EF Core 10 only logged it, so a source whose migrations assembly holds no migrations yet migrates alike on both framework lines), and replaces EF'sIModelCacheKeyFactorywithDataSourceModelCacheKeyFactory(:577) so each database and each contributor combination gets its own model.ConfigureSensitiveDataLogging(:594-602): a private helper called fromOnConfiguring. It callsoptionsBuilder.EnableSensitiveDataLogging()only whenSensitiveDataLoggingGate.IsEnabledsays bothPersistenceSettingsasked for it andIHostEnvironmentreports Development, both resolved withGetServiceso a design-time or directly-constructed context (which registers neither) reads as "off". Living on the shared base rather than in each engine's context class is what keeps the guarantee from holding for SQL Server while a fourth engine quietly leaks it.ConfigureConventions(:605-637): adds the model-finalization conventions in a fixed order.CrossDataSourceDegradeConvention(:614) strips FK constraints and navigations between entities in different physical databases (a structural no-op in the collapsed-monolith case);SoftDeleteUniqueIndexConvention(:620) makes unique indexes on soft-deletable entities exclude deleted rows, so a soft-deleted row does not block re-creating the "same" record (a hand-authored index filter is kept and extended: the soft-delete clause is appended with AND unless the filter already constrainsIsDeleted,:616-619);RestrictDeleteByDefaultConvention(:627) runs last of the three finalizing conventions, deliberately, so it never stamps a relationship the cross-source convention has already removed, and records on every foreign key whether its delete behavior was chosen or inherited, inverting EF's own cascade default for a required relationship nobody configured (:622-626); and, opt-in,StronglyTypedIdModelConfiguration.Apply(:634-636) runs only when aStronglyTypedIdRegistryis registered (AddStronglyTypedIds, ADR-115), mapping every declared wrapper type to the primitive it wraps on every engine because this runs on the one base context; absent the service it is a no-op and the primitive identifier aliases stay the identifier model.Set<TEntity>()(:639-641): a public override that forwards straight tobase.Set<TEntity>()and adds no behavior of its own.OnModelCreating(:644-667): runs theBeforeEntityPassescontributors first (:649), the auditable optional tables (a stored feature-flag override, a machine client, a webhook subscription), so the soft-delete filter and concurrency token applied next see them. It then applies soft-delete filters, tenant filters and concurrency tokens (:651-653), configures the outbox (passedphysicalDataSource.Key.Engine,:656), the inbox (:659) and the internal-command job queue (:662, one table per relational source like the outbox), and, last, runs theAfterEntityPassescontributors (:666): the job store, the change trail, refresh sessions, permission grants, view-as grants and passkeys, which no entity pass may touch. The base context names no optional table itself.ApplyModelContributors(:675-682): private; walks_modelContributorsand callsConfigure(modelBuilder, physicalDataSource.Key.Engine)on each whosePhasematches, in the orderOnConfiguringresolved them.ApplySoftDeleteFilters(:691-705):protected static; iterates every non-ownedIAuditableEntitytype and builds an expression-treeHasQueryFilter("SoftDelete", e => e.IsDeleted == false)(:697-703). Expression trees are required because the CLR type is only known at runtime; owned types are excluded because they inherit the parent filter.[Rubric §5, Vertical Slice](a global filter removes per-queryWhere(!IsDeleted)boilerplate from every slice).ApplyTenantFilters(:757-817):protected(instance, because the filter body reads this context). For every non-ownedITenantEntityit configures the discriminator column as required, capped atTenantIdMaxLengthof 64 (:721) and non-Unicode (:774-777), indexes it only whenEngine.Capabilities.IsRelational(:786-796, so every engine but Cosmos), and buildsHasQueryFilter("Tenant", e => IsAllTenantsScope || EF.Property<string>(e, "TenantId") == CurrentTenantId)(:809-815). Four mechanisms are worth internalizing here. The filter embeds this context as a constant typed asApplicationDbContext(:764-766), which EF rewrites to the executing context at query compile time and liftsCurrentTenantIdandIsAllTenantsScopeinto SQL parameters, so two scopes on two tenants, and a system scope beside them, share one compiled model and still read the rows each is entitled to (:738-745). Anulltenant sees nothing: a requiredTenantIdnever equals null, so a scope that resolved no tenant reads no tenant-owned rows, and an unauthenticated request that simply carried no tenant can never widen itself to every tenant's data (:746-754). It reads the column throughEF.Propertyrather than a CLR member access (:800-807), which works for an explicitly implemented interface member and for a shadow property alike. And the supporting index follows the filter composition: an entity that is also anIAuditableEntitygets(TenantId, IsDeleted)because every read of it carriesTenantId = @tenant AND IsDeleted = 0, while a tenant-only entity keeps the single-column index (:779-796).ConfigureConcurrencyTokens(:831-851):protected(instance, because it reads this context'sEngine). WhenEngine.Capabilities.RowVersionisRowVersionStrategy.StoreGenerated(:834, SQL Server'srowversion) it appliesIsRowVersion(); on the other relational engines, PostgreSQL and SQLite, it appliesIsConcurrencyToken()(:842-849), to theRowVersionproperty of every non-owned auditable entity. The doc comment (:819-830) names who manages the value on those engines:AuditSaveChangesInterceptorwrites a fresh value on every insert and update (it checksRowVersionStrategy.ClientStamped,AuditSaveChangesInterceptor.cs:67), so theUPDATE'sWHEREclause actually detects a concurrent writer. EF then includes the token inUPDATE/DELETEWHEREclauses and throwsDbUpdateConcurrencyExceptionon conflicts.[Rubric §8, Data Architecture].QuoteColumnandIncludeColumns(:853-889): two private static helpers the filtered outbox and internal-command indexes below route through, each a one-line delegation to the engine.QuoteColumn(DataSource engine, string column)(:861-862) forwards toSoftDeleteFilterSql.QuoteColumn, and its doc comment (:853-856) states the result: brackets on SQL Server, SQL-standard double quotes on PostgreSQL and SQLite.IncludeColumns(:885-889) forwards toDataSourceEngines.For(engine).IncludeColumns, which picks the provider's ownIncludePropertiesoverload (the SQL Server and PostgreSQL extensions share one signature and are ambiguous unqualified once both are referenced). Its remarks (:874-884) record two deliberate choices: every engine other than PostgreSQL keeps the SQL Server annotation, SQLite included because its provider ignores it, and the helper is the non-generic overload taking property names rather than a selector, so one helper serves every entity type.ConfigureOutbox(:902, takingDataSource engine, which per its doc comment:897-901shapes only the three partial-index predicates and the included-column annotation): mapsOutboxMessagesindbowith length/unicode constraints, including the explicit dead-letter state (DeadLetteredOnand a shortDeadLetterReason,:918-919), the request's W3C trace flags as a nullableTraceFlagscolumn (:924, expand-only, so a row written before it existed reads as not sampled), the captured ambient-context columns (tenant, roles, correlation id,:932-934), andUserPermissions(:939), which is deliberately left unbounded (nvarchar(max)on SQL Server) because a truncated permission list would deny deferred work the inline request was allowed to run. Every captured column is nullable, so adding it is expand-only and older rows read back as "nothing captured" (:927-931).ConfigureInternalCommandsmaps the same columns the same way (:1035,:1037) so the two hops carry identical values. The method also adds three purpose-built filtered indexes, built throughQuoteColumn/IncludeColumnsso the same method body produces valid filter and include syntax on every relational engine.IX_OutboxMessages_Pending(:944-950) covers the poll path over(ProcessedOn, OccurredOn)filtered to the processed column being null and includesDeadLetteredOnandLockedUntilso the processor's extra predicates do not force a key lookup per candidate row;IX_OutboxMessages_Processed(:955-957) covers the retention sweep over rows the pending index deliberately excludes; andIX_OutboxMessages_Ordering(:964-969) over(OrderingKey, OccurredOn), filtered to keyed pending rows, answers the claim predicate's "is there an earlier unprocessed row with this key?" question with a seek instead of a scan per candidate row.[Rubric §12, Performance & Scalability].ConfigureInbox(:977-1004): mapsInboxMessagesindbowith a requiredConsumercolumn capped atInboxConsumerNameAttribute.MaxLengthand defaulted to''in the database (:987-991), so a backfilled row reads as "every handler of this message already ran"; a uniqueIX_InboxMessages_MessageId_Consumerover(MessageId, Consumer)(:996-998, the consumer-side idempotency key, one row per message and handler); and anIX_InboxMessages_ProcessedOnindex (:1002-1003) so the age-based purge has something to seek.ConfigureInternalCommands(:1021-1064): mapsInternalCommandMessagetoInternalCommandsindboin every relational source, ungated, so flippingInternalCommands:Enabledis never a migration (:1006-1013). Its three filtered indexes areIX_InternalCommands_Pending(:1045-1051, includingAttemptsandClaimedUntil),IX_InternalCommands_Processed(:1056-1058) andIX_InternalCommands_DeadLettered(:1061-1063).ApplyConfigurationsForEntitiesInContext(:1073-1107): the discovery method subclasses call from theirOnModelCreating. It asks the engine for its configuration interface (DataSourceEngines.For(dataSource).EntityConfigurationInterface,:1075) rather than switching on theDataSourcevalue, resolvesIEntityDataSourceRegistry(:1082), then for each assembly from the provider callsModelBuilderExtensions.ApplyAllConfigurationswith a filter that keeps only entities whose registry-resolved key equals thisDataSourceKey, or, for unregistered entities, only when this context is the engine'sDefaultsource (:1098-1100). The whole pass runs inside atry/finallythat setsEngineAnnotationto this context's engine on the model first (:1089) and removes it afterwards (:1105). The comment (:1084-1088) gives the reason: a configuration declared for one engine can be applied to another engine's model when the host substitutes an unconfigured engine, so it cannot trust its own attribute for SQL text and reads the effective engine from the annotation instead; removing it keeps the finished model and every migration snapshot unchanged.
- Primary constructor (
- Why it's built this way:
ADR-006 (database-per-service)
requires the same context class per database; without a specialized model-cache key EF would build
one model and silently reuse it, so queries would hit tables that do not exist in the other
databases. The single
ApplicationDbContextis deliberately never split into per-module context classes (also ADR-006). The interceptor pipeline keeps audit, tenancy and outbox concerns out of every handler (ADR-073 for the tenancy model, ADR-075 for the trail). The optional tables are model contributors (ADR-148): each feature'sAddXcall registers its ownIModelContributor, so a host that never opted in keeps the exact base model and its migrations never see the table, a new optional table is a new contributor rather than an edit to this class, and the cache key follows the applying contributor types without a per-table bit to maintain. PostgreSQL joins SQL Server and SQLite as a third relational engine under ADR-113; the internal-command job queue is configured on every relational source the same way the outbox is (ADR-114); strongly typed identifiers apply only when a host opts in (ADR-115); and the restrict-by-default delete convention inverts EF's own cascade default for every non-owned foreign key (ADR-119). Every engine-specific branch reads the engine object behindEnginerather than comparingDataSourcevalues inline (ADR-130), so a fact about an engine is stated once, on that engine. The comment above the registry lookup (:1077-1081) records one more deliberate fallback: an entity configured without the attributed base classes lands in theDefaultmodel but is not routable through the unit of work. - Where it's used: inherited by the four concrete contexts below; created per source by
PhysicalDbContextFactorythrough the engine'sCreateDbContext(PhysicalDbContextFactory.cs:32), cached per scope and given its accessors byDbContextFactory(DbContextFactory.cs:152-157), and consumed by the interceptors and the outbox processor. The contributor gates are pinned bySchedulerModelGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Scheduling/SchedulerModelGateTests.cs:32),AuditTrailModelGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/AuditTrail/AuditTrailModelGateTests.cs:33),RefreshSessionModelGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/RefreshSessionModelGateTests.cs:45,:61) andPermissionGrantModelGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/PermissionGrantModelGateTests.cs:45,:61), and the contributors' coverage by the cache key byModelCacheKeyGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/ModelCacheKeyGateTests.cs:155,:170); the tenant filter byApplicationDbContextTenantFilterTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Tenancy/ApplicationDbContextTenantFilterTests.cs:27,:41,:59,:72,:87,:99,:121,:141,:156,:168,:181,:196,:209,:221), which covers cross-tenant hiding, composition with soft delete, a null tenant seeing no rows, an all-tenants scope seeing every row and sharing the tenant model, two tenants sharing one cached model, the live accessor being read at query time, the composite(TenantId, IsDeleted)index and the single-column one, owned types getting no filter of their own, and both named filters being declared.
DataSourceModelCacheKeyFactory
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/DataSourceModelCacheKeyFactory.cs:23· Level 8 · class (sealed)
- What it is: a replacement for EF Core's default
IModelCacheKeyFactory. Where the default keys the model cache by context type alone, this keys by(context type, data source name, model contributor key, strongly typed identifier key, design-time flag), so each physical database, and each combination of applying model contributors and declared identifier wrappers, gets its own EF model. - Depends on:
ApplicationDbContext(to readDataSourceKey.Name,ModelContributorKeyandStronglyTypedIdModelKey) and EF Core'sIModelCacheKeyFactory. - Concept introduced, model caching under one-context-class-per-engine.
[Rubric §8, Data Architecture]: EF builds an in-memory model perDbContexttype and caches it. When the same class serves two databases, EF would reuse the first model and the second database's entities would be missing. InsertingDataSourceKey.Nameinto the cache key makes EF treat "SQL Server / Conference" and "SQL Server / Identity" as distinct models. The class comment states both failure modes plainly (DataSourceModelCacheKeyFactory.cs:14-20): without the source name, queries would target tables that do not exist in the other databases; without the contributors, a process that builds two differently opted-in models (design-time model tests, for one, or two test hosts) would get whichever was built first for both, because contributor sets are fixed per host while EF's model cache is process-wide. This is the critical enabler for ADR-006. - Walkthrough:
Create(DbContext context, bool designTime)(DataSourceModelCacheKeyFactory.cs:26-33) returns(context.GetType(), applicationDbContext.DataSourceKey.Name, applicationDbContext.ModelContributorKey, applicationDbContext.StronglyTypedIdModelKey, designTime)when the context is anApplicationDbContext(:27-32), otherwise falls back to(context.GetType(), designTime)(:33). The value tuple's structural equality is all EF needs to key its cache dictionary. Both added members are safe to read here because EF builds the key afterOnConfiguringhas run on the same instance, and this factory is itself installed there, so the contributor list it reads is final (:19-20). The contributor key is the applying contributors' type names, never their state, and the identifier key is the declared types' names, never the registry instance, so two registries that declare the same types share one model (ApplicationDbContext.cs:114,:118). - Why it's built this way: the fix is minimal and lives entirely in Infrastructure through EF's
supported extension point; no EF internals are subverted. Note what is deliberately absent from
the key: the tenant. One compiled model serves every tenant, and the tenant value enters as a SQL
parameter through the
Tenantquery filter instead (seeApplicationDbContext.ApplyTenantFiltersand its remarks atApplicationDbContext.cs:738-745), which is what keeps a multi-tenant host from building one model per tenant. The applying contributors, by contrast, must be present: each one adds a table, and a contributor missing from the key lets the first-built model decide for every later context that differs only in it. Because the key carries contributor types rather than a fixed list of gates, a new optional table under ADR-148 needs no change here (ApplicationDbContext.ModelContributorKey,ApplicationDbContext.cs:99-113). - Where it's used: registered in
ApplicationDbContext.OnConfiguringviaoptionsBuilder.ReplaceService<IModelCacheKeyFactory, DataSourceModelCacheKeyFactory>()(ApplicationDbContext.cs:577), so every engine context inherits it. The key's coverage is pinned byModelCacheKeyGateTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/ModelCacheKeyGateTests.cs:142,:155,:170,:181,:190), whoseEveryFrameworkContributor_IsCoveredByTheKeyTheory(:170) fails on a framework contributor the key theory does not exercise.
IModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/IModelContributor.cs:40· Level 8 · interface
- What it is: the extension point that adds an optional table (or any other model configuration)
to the EF model of the relational contexts it applies to (
IModelContributor.cs:7-16).ApplicationDbContextresolves every registered contributor inOnConfiguring, keeps the ones whoseAppliesToaccepts the context's physical source, and runs them fromOnModelCreatinginPhaseorder. Every optional table the framework ships is one:PermissionGrantModelContributor,FeatureFlagOverrideModelContributor,ViewAsGrantModelContributor,PasskeyCredentialModelContributor,MachineClientModelContributor,WebhookSubscriptionModelContributor,ScheduledJobModelContributor,AuditTrailModelContributorandRefreshSessionModelContributor. - Depends on:
ModelContributorPhase,PhysicalDataSource,DataSourceand EF Core'sModelBuilder. - Concept introduced, an open extension point for the framework's own optional tables.
[Rubric §8, Data Architecture]and[Rubric §3, Clean Architecture]: the base context does not name the optional tables; each feature brings its mapping and its gate with it, so a new optional table is a new contributor, never an edit to the base context (:14-15). A host that registers no contributor, or whose contributors all decline a source, builds exactly the base model there, and that database's migrations never see a table it did not opt into. - Walkthrough:
Phase(:46): theModelContributorPhasethe contribution runs in, before or after the soft-delete, tenant and concurrency passes; contributors sharing a phase run in registration order.AppliesTo(PhysicalDataSource source)(:56): whether this contribution belongs in the model of the context targetingsource, typically "the feature is enabled ANDsourceis the database its settings name", so every other database's model stays byte-identical. Called once per context instance, before the model is built or fetched from the cache (:48-55).Configure(ModelBuilder modelBuilder, DataSource engine)(:67): adds the contribution to the model being built. It runs at most once per cached model, so it must be a pure function of the contributor's type andengine(:58-66); the engine is handed in for the engine-shaped parts of a mapping, filtered-index identifier quoting and included columns.- Registration rules (
:17-25): register it as a singleton, idempotently, from the same call that turns the feature on, withTryAddEnumerable(ServiceDescriptor.Singleton<IModelContributor, MyContributor>()). A contributor is resolved from the root provider (contexts are built by a singleton factory), so it cannot take a scoped dependency. Fordotnet ef, the same contributor is added throughDesignTimeDbContextOptions.AddModelContributor(DesignTimeDbContextOptions.cs:269), or the scaffolded migrations and the running model disagree.
- Why it's built this way: the model cache keys on the contributor types that apply, in
application order, never on contributor state (
:26-34,DataSourceModelCacheKeyFactory). So anything that should change the model belongs inAppliesTo, which decides whether the type joins the key, or in a distinct contributor type; aConfigurethat read a setting could hand a second, differently configured host in the same process the first host's cached model. The rule is EF's ownOnModelCreatingcontract, restated for the extension point. Contributors are relational-only (:35-38): Cosmos DB never runs the base model pipeline, soOnConfiguringresolves none there (ApplicationDbContext.cs:550-554). The decision is recorded in ADR-148. - Where it's used: resolved by
ApplicationDbContext.OnConfiguring(ApplicationDbContext.cs:550-554) and run by its privateApplyModelContributors(ApplicationDbContext.cs:675-682). Registered by the feature calls:DependencyInjection.Auth.cs:192(permission grants),DependencyInjection.FeatureFlags.cs:73(feature-flag overrides),DependencyInjection.Jobs.cs:52(job store) and:125(change trail),DependencyInjection.MachineClients.cs:50(machine clients), andDependencyInjection.cs:197,:212,:223(refresh sessions, view-as grants, passkeys), all underMMCA.Common/Source/Core/MMCA.Common.Infrastructure/. Idempotent registration is pinned byDependencyInjectionModelContributorTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/DependencyInjectionModelContributorTests.cs:43,:59,:75).
CosmosDbContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/CosmosDbContext.cs:15· Level 8 · class (sealed)
- What it is: the
sealedApplicationDbContextsubclass targeting Azure Cosmos DB. One instance exists per physical Cosmos data source (account plus database). It is the most divergent of the concrete contexts because Cosmos is non-relational: no outbox table, no relational indexes, no model contributors, and a truncatedOnModelCreatingpath. - Depends on:
ApplicationDbContext,PhysicalDataSource,DataSource,OutboxMessage,InternalCommandMessage,IEntityConfigurationAssemblyProvider, and the Cosmos EF provider (Microsoft.Azure.Cosmos).[Rubric §8, Data Architecture](one concrete context per engine) and[Rubric §11, Security](the emulator-only certificate bypass). - Walkthrough:
- 4-arg constructor (
CosmosDbContext.cs:15-20): forwards options, service provider, assembly provider, and physical source to the base. - Emulator handling in
OnConfiguring(CosmosDbContext.cs:22-73): two decisions, deliberately separate (:29-31). The emulator account key alone (UsesEmulatorKey,:32) selectsConnectionMode.Gateway(:44). Disabling certificate validation additionally requires a loopback endpoint (ShouldBypassCertificateValidation,:33), because the key is published by Microsoft and so never proves the endpoint is the local emulator; only then does anHttpClientFactoryinstallDangerousAcceptAnyServerCertificateValidatorunder a#pragma warning disable S4830(:46-61). The production path usesConnectionMode.DirectwithMaxRequestsPerTcpConnection(20)andMaxTcpConnectionsPerEndpoint(32)(:66-68). The database name comes fromPhysicalSource.CosmosDatabaseName(:38). UsesEmulatorKey(:82-83) andShouldBypassCertificateValidation(:98-99):internal staticpredicates. The first is an ordinalContains("C2y6yDjf5"), the well-known prefix of the emulator's default account key. The second requires that key AND a loopbackAccountEndpoint, judged by the privateHasLoopbackAccountEndpoint(:101-116): the connection string is parsed withDbConnectionStringBuilderand the endpoint withUri.TryCreate, then tested withUri.IsLoopback, never by a string prefix, so a host such aslocalhost.attacker.exampledoes not qualify, and an unparseable string or endpoint keeps validation on (:93-97).- No outbox override: the class overrides nothing to opt out of the outbox. Cosmos is
non-relational on its engine object, and
DomainEventSaveChangesInterceptortestsEngine.Capabilities.IsRelational(DomainEventSaveChangesInterceptor.cs:147,:259), so domain events from a Cosmos context are dispatched in-process only. The same capability makes the baseOnConfiguringresolve noIModelContributorfor a Cosmos context (ApplicationDbContext.cs:550-554). OnModelCreating(CosmosDbContext.cs:119-147): applies the Cosmos configurations (:121), thenIgnore<OutboxMessage>()(:124) and, for the same relational-only reason,Ignore<InternalCommandMessage>()(:127), then removes every index from every entity type because the provider does not support relationalHasIndex/HasFilter(:133-137), then callsApplySoftDeleteFiltersandApplyTenantFiltersdirectly (:145-146). It deliberately does not callbase.OnModelCreatingbecause every table the base maps (outbox, inbox, internal commands, and every optional table a model contributor adds) is a relational-only construct the Cosmos provider cannot express, so no contributor runs here (:139-144). Soft-delete and tenant filters are applied independently via the extracted helper methods; the tenant helper skips only its index for Cosmos, which indexes every property itself.
- 4-arg constructor (
- Why it's built this way: pushing all provider differences into this subclass keeps the base and
the entity configuration bodies engine-agnostic; stripping indexes lets one configuration body serve
both SQL Server and Cosmos. Calling the two filter helpers directly rather than through the base is
what keeps soft delete and tenancy in force on an engine that cannot run the rest of the base
pipeline (the tenant helper skips its index on a non-relational engine,
ApplicationDbContext.cs:786-796). - Where it's used: instantiated per Cosmos source by
CosmosDataSourceEngine.CreateDbContext(CosmosDataSourceEngine.cs:78-82), whichPhysicalDbContextFactoryreaches throughDataSourceEngineswhen a data source resolves to theCosmosDBengine (PhysicalDbContextFactory.cs:32). The emulator predicates are pinned byCosmosDbContextTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/CosmosDbContextTests.cs). - Caveats / not-in-source: Gateway mode is selected by an ordinal substring match on the emulator key prefix alone, while the certificate bypass also requires a loopback endpoint. Per ADR-018 the plumbing ships and is tested, but no host in this workspace configures a Cosmos source today.
PostgreSQLDbContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/PostgreSQLDbContext.cs:24· Level 11 · class (sealed)
- What it is: the
sealedApplicationDbContextsubclass targeting PostgreSQL, the third relational engine alongside SQL Server and SQLite (PostgreSQLDbContext.cs:24-35). One instance exists per physical PostgreSQL data source. - Depends on:
ApplicationDbContext,PhysicalDataSource,DataSource,IEntityConfigurationAssemblyProvider,PersistenceSettingsviaIOptions<>,UtcDateTimeConverter,NpgsqlDataSources(and, through it, any registeredINpgsqlDataSourceConfigurator), and the Npgsql EF provider.[Rubric §8, Data Architecture](a third concrete context, same shape as SQL Server) and[ADR-113](https://ivanball.github.io/docs/adr/113-postgresql-as-a-first-class-engine.html). - Walkthrough:
TimestampWithTimeZone(PostgreSQLDbContext.cs:35):internal const stringholding"timestamp with time zone", the PostgreSQL store type everyDateTimemaps to. Named as a constant so the context and its tests assert the same string rather than a repeated literal._persistenceSettings(:44-45): resolved once per instance in a field initializer, for the same CS9107 reason documented onSQLServerDbContext: reading the primary constructor parameter from a member body would capture it into this type's state while the base constructor also receives it.GetService, notGetRequiredService, so the design-time provider behinddotnet ef(which registers no options at all) falls back toPersistenceSettings' defaults._serviceProvider(:53): an explicit field copy of the primary constructor parameter, for the same CS9107 reason, soOnConfiguringcan look the shared data source up. The doc comment (:47-52) records that the data source itself is deliberately not held in a field: the container owns and disposes it, and a context must not.OnConfiguring(:56-80): asksNpgsqlDataSources.Resolve(_serviceProvider, PhysicalSource.ConnectionString)(:63). When that returnsnull(noINpgsqlDataSourceConfiguratorregistered, or the design-time provider) it callsUseNpgsql(PhysicalSource.ConnectionString, ConfigureNpgsql)(:66), the raw connection-string path; otherwiseUseNpgsql(dataSource, ConfigureNpgsql)(:70), so EF runs on the shared data source with its password provider included. Both branches pass the same options action, so a host that registers no configurator sees exactly the connection-string behavior (:60-62). It then appliesConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning))(:77), which suppresses the same microservices-extraction warning documented onSQLServerDbContext.ConfigureNpgsql(:82-106): the private options action both branches share. It conditionally setsnpgsql.MigrationsAssembly(PhysicalSource.MigrationsAssembly)(:87-90, the same "no migrations next to the context" contract as SQL Server and SQLite, a single shared property onPhysicalDataSourcerather than a per-engine one), appliesnpgsql.CommandTimeout(_persistenceSettings.CommandTimeoutSeconds)(:94), and enablesnpgsql.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorCodesToAdd: null)(:102-105) for the same transient-failure reason SQL Server does (connection drops, a managed instance failover, a pooler recycling a backend), with the sameDatabase.CreateExecutionStrategy().ExecuteAsynccaveat for manualBeginTransactionAsynccalls, already honored byTransactionalCommandDecorator<TCommand, TResult>.ConfigureConventions(:116-126): callsbase.ConfigureConventionsthen adds the UTC normalization every PostgreSQL timestamp needs:Properties<DateTime>().HaveConversion< UtcDateTimeConverter>().HaveColumnType(TimestampWithTimeZone). Declared as a type-mapping configuration rather than property-by-property so it reaches the framework's own tables (outbox, inbox, scheduled jobs, audit trail, refresh sessions) and a consumer's entities alike, including nullableDateTimeproperties, which EF configures from the same non-nullable entry.OnModelCreating(:129-133): callsApplyConfigurationsForEntitiesInContext(DataSource .PostgreSQL, modelBuilder)thenbase.OnModelCreating, so the full base pipeline (soft-delete and tenant filters, application-managed concurrency tokens, outbox/inbox/internal-command tables, and the four settings-or-registration-gated tables) runs.
- Why it's built this way: shares the SQL Server shape (retry, command timeout, pending-model-
changes suppression) because both are production-grade relational engines under
ADR-113; the
PostgreSQL-specific additions are the timezone-aware timestamp conversion, which exists because
Npgsql maps
DateTimetotimestamp without time zoneby default while the framework's audit and outbox timestamps are always UTC, and the optional shared data source, which is the only way EF can carry a builder-level password provider (an IAM token) supplied by a cloud adapter (ADR-134). - Where it's used: instantiated per PostgreSQL source by
PostgreSQLDataSourceEngine.CreateDbContext(PostgreSQLDataSourceEngine.cs:89), whichPhysicalDbContextFactoryreaches throughDataSourceEngineswhen a data source resolves to thePostgreSQLengine; built at design time byDesignTimeDbContextHelper. Its model is pinned byPostgreSQLDbContextModelTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/PostgreSQLDbContextModelTests.cs) and exercised against a real server byPostgreSQLPersistenceTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.PostgreSQL.Tests/PostgreSQLPersistenceTests.cs).
SqliteDbContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/SqliteDbContext.cs:12· Level 12 · class (sealed)
- What it is: the
sealedApplicationDbContextsubclass targeting SQLite, the minimal concrete context. One instance exists per physical SQLite data source (database file), useful for lightweight local development or testing without a SQL Server instance (SqliteDbContext.cs:7-10). - Depends on:
ApplicationDbContext,PhysicalDataSource,DataSource,IEntityConfigurationAssemblyProvider, and the SQLite EF provider. - Walkthrough: the 4-arg constructor forwards to the base (
SqliteDbContext.cs:12-17).OnConfiguringguards its argument, then callsUseSqlite(PhysicalSource.ConnectionString, ...)with one option: it setssqlite.MigrationsAssembly(PhysicalSource.MigrationsAssembly)when that value is configured (SqliteDbContext.cs:31-34), the same sharedPhysicalDataSourceproperty SQL Server and PostgreSQL now read instead of a per-engine one. The comment above it states the contract this shares with SQL Server (:28-30): without an explicit assembly EF looks for migrations next to the context, which lives inMMCA.Common.Infrastructureand has none, so a per-source migrations project would never be found. There is no retry policy (the store is file-local) and no command-timeout override.OnModelCreatingcallsApplyConfigurationsForEntitiesInContext(DataSource.Sqlite, modelBuilder)thenbase.OnModelCreating(SqliteDbContext.cs:40-44), so unlike Cosmos it keeps the full base pipeline: soft-delete and tenant filters, concurrency tokens as application-managed tokens rather thanrowversion, the outbox and inbox tables, and the three settings-gated tables. SeeSQLServerDbContextfor the shared subclass shape. - Why it's built this way: SQLite needs none of the SQL Server hardening (transient-failure retry,
a per-environment command timeout), so the override is intentionally sparse, but the migrations
assembly is not optional hardening: it is what lets a SQLite source participate in
IDbContextFactory.MigrateAsyncat all, sincePhysicalDataSource.UsesMigrationsreturnstruefor SQLite only when that assembly is configured (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/PhysicalDataSource.cs:41-47). Keeping the full base pipeline is what makes this context a faithful stand-in for SQL Server in tests, which is how the framework's own tenancy and model-gate suites run without a database (for exampleMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Tenancy/ApplicationDbContextTenantFilterTests.cs:24, which holds one SQLite connection open for the fixture's lifetime).[Rubric §14, Testability]. - Where it's used: instantiated per SQLite source by
PhysicalDbContextFactorywhen a data source resolves to theSqliteengine (PhysicalDbContextFactory.cs:32dispatches toSqliteDataSourceEngine.cs:88). Its migration behavior is pinned byDbContextFactoryMigrationTargetTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/DbContextFactoryMigrationTargetTests.cs:94,:106,:115,:126), which asserts that a SQLite source with a migrations assembly is migrated, one without is skipped,HasPendingMigrationsAsyncconsiders only the migrated source, andEnsureCreatedAsyncstill covers both.
SQLServerDbContext
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/SQLServerDbContext.cs:15· Level 12 · class (sealed)
- What it is: the
sealedApplicationDbContextsubclass targeting SQL Server, the production-primary context. One instance exists per physical SQL Server data source (database); its connection string and migrations assembly come from the resolvedPhysicalDataSource. - Depends on:
ApplicationDbContext,PhysicalDataSource,DataSource,IEntityConfigurationAssemblyProvider,PersistenceSettingsviaIOptions<>, and the SQL Server EF provider (RelationalEventId).[Rubric §8, Data Architecture](one concrete context per engine, one instance per database) and[Rubric §29, Resilience & Business Continuity](the retry policy and the command timeout are baked into the SQL Server path). - Walkthrough:
- 4-arg constructor (
SQLServerDbContext.cs:15-20): forwards to the base. _persistenceSettings(SQLServerDbContext.cs:35-36): a readonly field resolved in the field initializer asserviceProvider.GetService<IOptions<PersistenceSettings>>()?.Value ?? new PersistenceSettings(). Two details are deliberate and documented at:23-35. It is resolved once per instance rather than read from the primary-constructor parameter insideOnConfiguring, because referencing that parameter from a member body would capture it into the type's state while the base constructor also receives it (CS9107); caching per instance is safe precisely because these contexts are never pooled. And it usesGetService, notGetRequiredService, because the design-time provider behinddotnet efregisters no options at all and must not be made to throw: both a missing registration and a null value fall back to the defaults.OnConfiguring(SQLServerDbContext.cs:39-82): callsUseSqlServer(PhysicalSource.ConnectionString, sql => ...). The options action does three things: conditionally setssql.MigrationsAssembly(PhysicalSource.MigrationsAssembly)(:49-52), the same single property PostgreSQL and SQLite now read instead of a per-engine one, so each extracted service can point at its own per-module migrations project; appliessql.CommandTimeout(_persistenceSettings.CommandTimeoutSeconds)(:56), because without it every command silently inherits ADO.NET's 30 second default with no way to tune it per environment (the setting's own default is30, range-validated to 1-600, atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/PersistenceSettings.cs:21-22); and enablessql.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null)(:64-67). An inline comment (:61-63) records the retry caveat: with retry enabled, any manualBeginTransactionAsyncmust be wrapped inDatabase.CreateExecutionStrategy().ExecuteAsync, whichTransactionalCommandDecorator<TCommand, TResult>already does throughDbContextFactory. FinallyConfigureWarnings(w => w.Ignore(RelationalEventId.PendingModelChangesWarning))(:80) suppresses EF Core's pending-model error.OnModelCreating(SQLServerDbContext.cs:85-89): callsApplyConfigurationsForEntitiesInContext(DataSource.SQLServer, modelBuilder)thenbase.OnModelCreating, so the full base pipeline (soft-delete and tenant filters,rowversionconcurrency tokens, outbox/inbox tables, and the three settings-gated tables) runs.
- 4-arg constructor (
- Why it's built this way: the
PendingModelChangesWarningsuppression is required by the microservices-extraction design: each extracted host registers only its enabled modules' configurations, so its runtime model is a strict subset of the migration snapshot (the union of all modules), and EF Core 9+ would otherwise promote that mismatch to an error insideMigrator.ValidateMigrationsduringMigrateAsync(SQLServerDbContext.cs:68-74). The documented trade-off (:77-79): monolith hosts lose the "you forgot a migration" safety net, so CI should rundotnet ef migrations has-pending-model-changesagainst the migrations assembly with the full model loaded as a separate gate. Retry-on-failure exists so cold-replica startup connections and platform replica replacements do not surface as user-facing 5xx (ADR-006, ADR-009). - Where it's used: instantiated per SQL Server source by
PhysicalDbContextFactory(PhysicalDbContextFactory.cs:32dispatches toSQLServerDataSourceEngine.cs:91); built at design time byDesignTimeDbContextHelper.CreateSqlServer(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:64), which is what makes one migrations project per database possible. It is also the typeDbContextFactorytests for on the identity-insert path (DbContextFactory.cs:269). It is the primary production context in both MMCA.ADC and MMCA.Store, and the context type every committed migration snapshot is generated against. - Caveats / not-in-source: whether any repository's CI actually runs the
has-pending-model-changesgate the comment recommends is Not determinable from this file.
EncryptedStringConverter
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Encryption·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Encryption/EncryptedStringConverter.cs:76· Level 0 · class (sealed)
- What it is: an EF Core
ValueConverter<string, string>that encrypts a string property with AES-256-GCM on the way to the database and decrypts it on the way back, transparently to the entity (EncryptedStringConverter.cs:9-12). It is applied per property in an entity configuration, not globally (:12-18), and the value it stores is a versioned envelope: the key it decrypts with is named by a byte inside the stored value itself, not by whatever key the converter was built with. - Depends on:
System.Security.Cryptography(AesGcm,RandomNumberGenerator,CryptographicException),System.Collections.Frozen(FrozenDictionary,:1),System.Text.Encoding, and EF Core'sValueConverter<TModel, TProvider>. No first-party type. - Concept introduced, authenticated encryption at rest, and what it costs you.
[Rubric §11, Security](assesses whether sensitive data is protected in transit and at rest with sound primitives) and[Rubric §30, Compliance, Privacy & Data Governance](assesses whether personal data is classified and handled deliberately). AES-GCM is an authenticated mode: it gives confidentiality and integrity in one pass, so tampering with a stored value makes decryption throw instead of silently yielding garbage, and no separate HMAC step is needed. The price is stated at length in the class comment (:19-32) and is the part worth internalizing: every write draws a fresh random nonce (:223), so the same plaintext produces a different column value each time. A non-deterministic column cannot carry an equality or range predicate (the comparison is against a ciphertext that never matches, and the query returns no rows rather than failing), cannot carry a unique index, and cannot be sorted or grouped server side. Anything that must stay searchable needs a second, deterministic surface such as a keyed hash beside the encrypted column. This is the counterpart to the erasure story taught byIAnonymizableandPiiAttribute(ADR-005): erasure overwrites a field you never need again, encryption protects one you still have to read back. - Concept introduced, a self-describing envelope is what makes key rotation possible.
[Rubric §8, Data Architecture](assesses whether persistence mechanics are deliberate) and again[Rubric §11, Security]. A stored value is Base64 of[key version (1)] [nonce (12)] [ciphertext (N)] [tag (16)](:38-44, laid out at:233-238), so the row carries everything needed to read it back except the key material: 29 bytes of overhead before Base64 inflation (:79,:82,:85). Two properties fall out of that one byte. First, a converter can hold a whole key ring keyed by version with one version nominated as current (:113): writes stamp the current version (:120,:235), reads take their key from the version byte in the data (:253-254), so a rotation is add the new key as current, deploy, re-encrypt rows in the background (MarkForReEncryption,:143), then retire the old version, with no maintenance window and no rows left unreadable in between (:45-61). Second, the version byte is authenticated, not merely stored: it is passed to AES-GCM as associated data on both sides (:228,:261), so rewriting it fails the tag check rather than silently selecting another key, and it fails even when the substituted version happens to map to the same key. That last property is the one a "just prefix the version" design usually misses. - Walkthrough:
- Sizes and the default version (
EncryptedStringConverter.cs:79,:82,:85,:88,:91):VersionSize = 1,NonceSize = 12bytes (96 bits, the NIST recommendation for GCM),TagSize = 16bytes (128 bits),KeySize = 32bytes, andDefaultKeyVersion = 1, the version the single-key constructor stamps. - Two public constructors over one private one (
:98-101,:113-116,:118-123): thebyte[]constructor is sugar for a one-entry ring at version 1, built byCreateSingleKeyRing(:99,:157-168), which null-guards the key (:159) and rejects anything that is not exactly 32 bytes with a message naming the length it got (:160-165). The ring constructor takes anIReadOnlyDictionary<byte, byte[]>plus the version to write with. Both funnel into the private constructor, which passes the two lambdas up toValueConverter,Encryptas the to-provider direction bound to the current version andDecryptas the from-provider direction (:120-121). The frozen ring is captured by those lambdas. ValidateAndFreeze(:176-212): the ring is validated once, at construction. Not null (:180), not empty (:182-185), no null entry (:189-194), every key exactly 32 bytes (:196-201), and the nominated current version actually present (:204-209), which is what letsEncryptindex the ring without a lookup guard (:219-220). ThenToFrozenDictionary()(:211) takes a defensive copy, so mutating the dictionary the caller passed in afterwards cannot change which keys the converter uses (:170-175).GenerateKey()(:129):RandomNumberGenerator.GetBytes(32), the convenience path for producing a valid key during setup.MarkForReEncryption(EntityEntry)(:143-155): the rotation helper for the re-encrypt step. A column whose value did not change is left out of the UPDATE and would keep its old version byte, so this null-guards the entry (:145), walks its properties whose metadata converter is anEncryptedStringConverter(:148), setsIsModified = trueon each (:150), and returns how many it marked. The next save then rewrites those columns under the current key version. Owned types are tracked as entries of their own, so an encrypted property on an owned navigation needs that owned entry passed separately (:137-140). The only caller is its own test, which marks one encrypted property, saves, and checks the column is rewritten under the new version (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Encryption/EncryptedStringConverterReEncryptionTests.cs:26,:43).Encrypt(:214-241): empty and null pass through unchanged (:216-217), otherwise resolve the current key (:220), UTF-8 encode (:222), draw a 12-byte nonce (:223), and encrypt into a same-length ciphertext buffer with a 16-byte tag, handing the single version byte over as associated data (:224-231). The four regions are then laid into one buffer in envelope order (:233-238) and Base64-encoded (:240). Storing the version and nonce alongside the ciphertext is what makes each row self-describing: no side table of nonces and no out-of-band record of which key wrote which row.Decrypt(:243-269): Base64 decode (:248), reject anything shorter than version plus nonce plus tag with aCryptographicException(:250-251), read the version from position 0 and fail with a message naming only the version number (never key material) when the ring has no key for it (:253-255), then slice nonce, ciphertext, tag, and the associated-data byte by fixed offsets and decrypt (:257-266). A wrong key, a tampered ciphertext byte, and a rewritten version byte all fail insideAesGcm.Decrypt, which is the integrity guarantee doing its job.
- Sizes and the default version (
- Why it's built this way: GCM over CBC removes the "encrypt then MAC" bookkeeping that is easy to
get wrong, and putting the whole scheme behind a
ValueConvertermeans an entity property stays a plainstringin the domain model. ADR-037 records the decision and is explicit that this is a second layer above transparent database encryption: TDE decrypts for anyone who can query, this converter keeps the value ciphertext the moment it leaves the application. The key never lives in the converter's own configuration: the comment (:33-37) points at Key Vault, user-secrets, or environment variables. The converter is also deliberately stateless and context-free (:62-70): version resolution is data-driven from the envelope and nothing consults theDbContext, the current user, or any ambient scope, because a value converter is a pair of compiled expressions running in the provider's materialization path and cannot reach them. Per-tenant or per-request key selection is therefore out of scope here by design and needs aSaveChangesinterceptor or application-layer encryption above EF Core. - Where it's used: nowhere in application code today. A workspace-wide search of
*.csfor the type finds only its own file, its 21 unit tests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Encryption/EncryptedStringConverterTests.cs:6, covering the plaintext round trip at:10, non-determinism at:24and:38, key generation at:52and:61, the invalid-length and null-key guards at:71and:123, the empty-string passthrough at:82and:95, the too-short value at:108, Unicode at:129, the version byte the single-key constructor stamps at:145, a key-ring round trip at:157, a full rotation in which pre-rotation ciphertext stays readable while new writes carry the new version at:175, an unregistered version at:205, the tampered-version-byte failure at:226, the four ring-validation guards at:244,:250,:259, and:268, and the defensive copy of the caller's dictionary at:281), and one prose mention in theIAnonymizabledoc comment (MMCA.Common/Source/Core/MMCA.Common.Domain/Interfaces/IAnonymizable.cs:17-19) recommending it for personal fields that must survive erasure in readable form. No entity configuration callsHasConversion(new EncryptedStringConverter(...))in any of the repos, and no DI registration supplies a key or a ring. - Caveats / not-in-source: this is therefore a shipped but unadopted extension point, a posture
ADR-037 states
outright and still records as zero adoption after the versioned envelope shipped in MMCA.Common
v1.153.0. Zero adoption is also what made the format change affordable: there is no legacy decode
path, so a value written in the earlier un-versioned
[nonce] [ciphertext] [tag]layout does not read back under the current converter (its first byte is a nonce byte, not a version), and the window in which the envelope is free to change closes at the first adopted column. Three further limits are worth knowing before adopting it. The version space is a single byte (:79), ample for annual or quarterly rotation but wrapping rather than growing, and a reused version number is exactly the ambiguity the byte exists to prevent. The suite covers the short-value, unregistered-version, and rewritten-version failures but never flips a bit inside the ciphertext body or decrypts under a wrong key at the same version, so integrity over the ciphertext rests on the primitive rather than on a test. And the searchability constraint stands: the IdentityUserstoresEmailas a queried column (seeIdentityModuleDbSeederBase<TUser>, whose existence check is an EF predicate on that column), so encrypting it with this converter would silently break that lookup rather than fail loudly.
SeedAccount
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Seeding·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Seeding/SeedAccount.cs:18· Level 0 · record (sealed)
- What it is: the five-member positional record describing one development or test account for
IdentityModuleDbSeederBase<TUser>to create:(string Email, string Password, string Role, string? FirstName = null, string? LastName = null)(SeedAccount.cs:18-23). - Depends on: nothing. It is a pure data carrier with no framework types in its signature, which is what lets each app spell its own role vocabulary as a plain string.
- Concept introduced: none new. It is the parameter object of the template-method seeder taught in
IdentityModuleDbSeederBase<TUser>;[Rubric §11, Security]applies only through the notice below. - Walkthrough: the doc comments carry the contract for each member.
Emailis also the idempotency key, the value the "already seeded?" check compares against (:12).Passwordis plaintext and is hashed by the seeder before persistence (:13).Roleis the role as the app's own vocabulary spells it (:14), so ADC passesUserRole.Organizer.Valueand Store passes its own admin role without the framework knowing either.FirstNameandLastNameare nullable because not every app'sUsercarries them (:15-16). - Why it's built this way: a record rather than a tuple gives the five values names at every call site, and positional construction keeps an account list readable as a literal array (see the app lists cited below).
- Where it's used: the abstract
Accountsproperty ofIdentityModuleDbSeederBase<TUser>(IdentityModuleDbSeederBase.cs:80); supplied by ADC'sIdentityModuleDbSeederas three accounts (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:33-38) and by Store's through aStoreAccountsarray (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:27,:34). - Caveats / not-in-source: the record's own remarks (
SeedAccount.cs:6-12) call the security property out: seed credentials are plaintext by construction, so an account list is development-only data that must be gated or replaced with environment-sourced secrets before a seeder runs in a deployed environment. Both apps' lists contain deliberately weak passwords.
TransactionCommitAmbiguousException
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/TransactionCommitAmbiguousException.cs:28· Level 0 · class (sealed)
- What it is: the exception
DbContextFactory.ExecuteInTransactionAsyncthrows when the commit phase fails, meaning the transaction may or may not have become durable because a commit can fail after the database applied it but before the acknowledgement reached the client (TransactionCommitAmbiguousException.cs:3-7). - Depends on: the BCL
Exceptiononly. - Concept introduced, an unknown outcome is a distinct failure mode.
[Rubric §29, Resilience, Reliability & Business Continuity Concerns](resilience policies applied through a shared mechanism rather than per call) and[Rubric §29, Resilience & Business Continuity](assesses whether failure modes are identified and handled deliberately): a generic failure would be wrong twice over. First, mechanically: SQL Server'sEnableRetryOnFailurestrategy (configured atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/SQLServerDbContext.cs:63-66with five retries and a 10 second ceiling) classifies most commit-phase errors (timeouts, dropped connections) as transient, and EF decides retriability by walking an exception's whole inner chain, so any wrapper carrying the transient error would still be retried, re-running every write of an operation whose commit may already be durable, including its outbox rows (TransactionCommitAmbiguousException.cs:8-14,DbContextFactory.cs:616-619). That is why the commit failure is returned rather than thrown fromRunTransactionalAttemptAsyncandTryCommit(DbContextFactory.cs:629-633,:572-574,:617-620) and only converted into this exception past the strategy (DbContextFactory.cs:620-621). Second, semantically: "it failed" and "nobody can say whether it failed" call for different recovery, so the type itself is the signal. - Concept introduced, naming the partial outcome.
[Rubric §13, Observability & Operability](assesses whether an operator can tell what actually happened from what the system reports): commits across several physical sources are sequential and independent, so a failure part-way through leaves earlier sources durable. Rather than leave that inferable only from timing, the exception carries three lists that partition every source the failed commit touched. - Walkthrough:
DefaultMessage(TransactionCommitAmbiguousException.cs:30-32): states both halves, the unknown durability and the deliberate non-retry.- Five constructors (
:29-69): the parameterless,(string)and(string, Exception)standard set;(Exception innerException)(:45-46), which pairs the provider's failure with the default message; and the four-argument diagnostic one (:57-69), which additionally takes the committed, ambiguous and rolled-back sources and composes them into the message. That last one is the oneDbContextFactoryactually constructs (DbContextFactory.cs:782); it null-coalesces both lists to empty (:63,:66-68) so a caller passingnullgets an empty group rather than a second exception. CommittedSources(:76),AmbiguousSource(:85),RolledBackSources(:93): the three outcome groups, each with doc comments stating what a reader may conclude. Committed sources are durable, so the ambiguity is a partial commit and reconciliation means replaying only what the remaining sources owed (:71-75). The ambiguous source alone is unknowable, and with a single transactional source (the case every host runs today) it is the whole outcome while the other two groups are empty (:78-84). Rolled-back sources wrote nothing that survives, with "best-effort" spelled out literally: a rollback that itself throws is swallowed and the transaction abandoned to the server (:87-92).ComposeMessage(:99-118): builds at most three clauses, skipping any empty group, and appends" Per-source outcome: ..."to the default text; with nothing to report it returns the default message unchanged (:115-117), so a single-source failure reads as one clause rather than three.
- Why it's built this way, and what a caller does about it: the exception's own doc comment assigns
recovery to the caller (
TransactionCommitAmbiguousException.cs:15-26). An API request marked[Idempotent]replays safely; whatever the transaction wrote to the outbox is delivered by theOutboxProcessorif the commit did land (ADR-003); and the deferred in-process dispatch is dropped, so no handler acts on state that may not exist (DbContextFactory.cs:798-821). The source comment records that a witness row (a marker written inside each source's transaction that a replay could read) would close the multi-source gap entirely, and that it is deliberately not built, because the single transactional source every host runs today needs none (DbContextFactory.cs:567-577). - Where it's used: thrown at
DbContextFactory.cs:621, constructed at:646; pinned byDbContextFactoryCommitAmbiguityTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/DbContextFactoryCommitAmbiguityTests.cs:73,:105,:129,:149,:168), which drives a context whose execution strategy retries on any exception and asserts the operation runs exactly once, that nothing is dispatched in-process, that the transaction is abandoned, that an ordinary success path still commits and flushes, that a failure inside the operation is still retried, and that a second-source commit failure reports each source's outcome. - Caveats / not-in-source: nothing in the framework catches this type. Whether a host's exception middleware maps it to a specific HTTP status is Not determinable from source: no first-party handler references it outside the throw site and its tests.
ExplicitKeyInsertRoundOrder
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/ExplicitKeyInsertRoundOrder.cs:17· Level 0 · class (internal static)
- What it is: a pure ordering helper for the explicit-key insert path of
DbContextFactory. Given the entity types each insert round saves, it returns every round index exactly once, principals before dependents, so a round that holds a foreign key never saves before the round holding the table that key points at (ExplicitKeyInsertRoundOrder.cs:17). - Depends on:
Microsoft.EntityFrameworkCore.Metadata.IReadOnlyEntityTypeand BCL collections only; nothing first-party. - Concept introduced, ordering by the table dependency graph (Kahn's algorithm).
[Rubric §8, Data Architecture](transaction and write-ordering correctness): the change tracker yields entries in the order they were added, which says nothing about foreign keys, so saving one table per round in that order can violate a constraint.Order(:37) builds a graph whose nodes are rounds and whose edges are "this round has a foreign key into a table held by that round" (PrincipalRounds,:45; the table is the key,TableOf,:109, because several entity types can share one table), then runs a topological sort (TopologicalOrder,:79). - Walkthrough:
PrincipalRounds(:45-76): maps each(schema, table)to its round, then for each round collects the other rounds its foreign keys point at. A self-reference is no edge (principalRound != round,:67-68), since EF orders rows within one round itself.TopologicalOrder(:79-107): repeatedly takes the lowest-index round whose principals are all already placed (:87-94), so independent rounds keep their original order. When none qualifies the graph has a cycle, which has no valid order; the lowest-index unplaced round is taken to break it (:96-100), which keeps the result deterministic.
- Why it's built this way: determinism is the point. A stable tie-break (lowest index) means the same input always saves in the same order, and a cycle degrades to a defined order instead of an exception.
- Where it's used:
DbContextFactory.SaveWithExplicitKeyInsertAsynccalls it once per explicit-key save and reorders its groups by the result (DbContextFactory.cs:344). The ordering is pinned byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/Factory/ExplicitKeyInsertRoundOrderTests.cs.
DbSeeder
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Seeding·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Seeding/DbSeeder.cs:11· Level 8 · class (abstract)
- What it is: the abstract base every concrete database seeder derives from. It implements no
interface (
DbSeeder.cs:11): it declares the seeding contract itself, a single abstractTask SeedAsync(CancellationToken)(DbSeeder.cs:18), and adds two pieces of shared machinery: a converter from anintseed id to whatever identifier type the module uses, and a save that tolerates a concurrent replica seeding the same rows (DbSeeder.cs:6-10). - Depends on:
IUnitOfWork,IUniqueConstraintViolationDetectorandSqlServerUniqueConstraintViolationDetectorfor the lost-race check, EF Core'sDbUpdateException,ChangeTrackerandEntityState, plus the BCLGuid,BitConverter, andSpan<byte>. - Concept introduced, seed data across two identifier strategies.
[Rubric §15, Best Practices & Code Quality](assesses whether shared mechanics live in one place rather than being restated per module): the identifier-type alias taught in the primer means one module's key isintand another's isGuid(ADC'sSpeakerIdentifierTypeis aGuid, itsUserIdentifierTypeis anint). Seed data, however, is naturally written with small readable literals: category 1, room 2.GetId<T>(int)is the bridge, so a seeder can writeGetId<SpeakerIdentifierType>(3)and stay correct whichever alias the module picked. - Walkthrough:
SeedAsync(DbSeeder.cs:18): abstract,public, no default behavior, documented on the class itself (:13-17) since there is no interface member to inherit from. It is the seeder's whole contract: noIsEnabled, no ordering property, no result type, so a seeder either runs to completion or throws, and ordering comes from the caller. The base deliberately does not template the seeding flow itself; that isIdentityModuleDbSeederBase<TUser>'s job for the one flow that repeated across apps.GetId<TIdentifier>(int id)(DbSeeder.cs:28-47):protected static, constrained tonotnull. ForGuidit writes the int's four bytes into the start of a zeroed 16-bytestackallocspan and constructs aGuidfrom it (:31-39), which is deterministic: the same seed integer always produces the sameGuid, so re-running a seeder against an existing database matches the rows it wrote last time. Forintit is a boxed pass-through (:41-44). Anything else throwsNotSupportedExceptionnaming the type (:46).SaveToleratingConcurrentSeedAsync(IUnitOfWork, CancellationToken)(DbSeeder.cs:76-94):protected static, returningTask<bool>. It null-guards the unit of work (:80), callsSaveChangesAsyncand returnstrue(:84-85). A save that fails with a unique or primary-key violation (catch ... when (IsUniqueConstraintViolation(unitOfWork, exception)),:87) is read as a lost insert race: the failed save is discarded and the method returnsfalse(:91-92), so the caller can log the skip and carry on. Any other failure propagates.IsUniqueConstraintViolation(:97-99): classifies the exception with the unit of work's ownIUniqueConstraintViolationDetectorwhen it implements one (the host's engine-aware choice), else aSqlServerUniqueConstraintViolationDetectorbuilt on demand, because this runs only on a failed save (:96).DiscardFailedSave(:107-130): walks the exception chain to the firstDbUpdateException(:109-114) and, for each distinct context in itsEntries, detaches everyAdded,ModifiedorDeletedentry (:116-126). A failed save rolls back as a whole, so everything still pending there belongs to it; left tracked, the scoped context would replay the same rejected insert on the next save and fail again (:101-106).
- Why it's built this way:
protected statickeeps both helpers out of the public surface (a seeder is not a general-purpose id converter or save API) while still allowing every derived seeder to use them without an instance. Determinism, not uniqueness, is the property that matters forGetId: seeders must be idempotent across restarts, which is what production hosts rely on when they run the seeder on every boot (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:139). Idempotence across restarts is not enough across replicas: seeding is check-then-insert, so two replicas starting together on a database that lacks a row both pass the existence check and both insert, and the slower save is rejected by the unique index or primary key. That rejection is not a fault, because the winner wrote the very rows this run meant to write, which is why the tolerant save lives here once for every seeder rather than in one subclass (DbSeeder.cs:53-68). - Where it's used: the base of every module seeder in both apps, for example ADC's
ConferenceModuleDbSeeder(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Infrastructure/Persistence/DbContexts/Seeding/ConferenceModuleDbSeeder.cs:43), Store'sCatalogModuleDbSeeder(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Infrastructure/Persistence/DbContexts/Seeding/CatalogModuleDbSeeder.cs:22) andSalesModuleDbSeeder(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Infrastructure/Persistence/DbContexts/Seeding/SalesModuleDbSeeder.cs:28), and the framework's ownIdentityModuleDbSeederBase<TUser>(IdentityModuleDbSeederBase.cs:54-57), which saves each account throughSaveToleratingConcurrentSeedAsync(IdentityModuleDbSeederBase.cs:131). A concrete seeder is constructed withnewinside its module'sIModuleSeeder, which reads configuration, resolves the unit of work, and callsSeedAsync(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:33-36);ModuleLoaderruns those throughSeedAllAsyncat startup. That keeps the configuration gate in the Application-layer contract that can seeIConfigurationand the row writing in this Infrastructure base that can see the unit of work. Pinned byDbSeederTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/Seeding/DbSeederTests.cs:9,:15,:23,:33,:42,:51), which assert the int pass-through,Guiddeterminism, distinctness across different ints, the unsupported-type throw, and thatSeedAsynccan be implemented, and by the tolerant-save tests:trueon success (:61),falsewith the failed save detached on a unique violation (:76), propagation with the entries still tracked on any other failure (:97), the unit of work's own detector preferred (:115), and the null guard (:134). - Caveats / not-in-source: the
Guidmapping consumes only the first four of sixteen bytes, so the produced values are structurally recognizable rather than random. That is intentional for seed data and is not a source of production ids: entity ids come from the database for an[IdValueGenerated]entity (SQLServerDataSourceEngine.cs:104) or from the entity's own factory, which is the only option on Cosmos DB, where an[IdValueGenerated]entity throws at model build (CosmosDataSourceEngine.cs:98-104,:113).
IDbContextFactory
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/IDbContextFactory.cs:10· Level 9 · interface
- What it is: the framework's own context-factory contract, the scoped object that hands out one
ApplicationDbContextper physicalDataSourceKeyand then coordinates saving, transactions, schema lifecycle, and disposal across every context a scope touched (IDbContextFactory.cs:5-10). It is deliberately not EF Core'sIDbContextFactory<TContext>: the two names collide, which is why consumers that need both add ausing IDbContextFactory = ...DbContexts.Factory.IDbContextFactory;alias (InProcessEventBus.cs:11,BrokerEventBus.cs:9,EfInboxStore.cs:8) or fully qualify it (OutboxProcessor.cs:202). - Depends on:
ApplicationDbContext,DataSourceKey, and the BCLIDisposableplusIAsyncDisposableit extends (IDbContextFactory.cs:10). - Concept introduced, addressing a context by physical source rather than by type.
[Rubric §8, Data Architecture](assesses whether transaction boundaries and unit-of-work scope are deliberate, and whether per-service data isolation is real): EF's own factory answers "give me a context of type T". This one answers "give me the context for this database", which is the only question that makes sense once ADR-006 splits storage along aNameaxis and ADR-018 adds an orthogonalEngineaxis. The interface also owns the honest statement of what a multi-source save can and cannot promise, in theExecuteInTransactionAsyncdoc comment (IDbContextFactory.cs:60-65): each physical source gets its own transaction, commits are sequential and best-effort, there is no two-phase commit, a failure mid-commit leaves earlier sources committed, and the outbox is the cross-source consistency mechanism. - Walkthrough:
GetDbContext(DataSourceKey)(IDbContextFactory.cs:16): the only accessor, documented to create the context if this scope does not already have one for that source.EnsureCreatedAsync(:22),MigrateAsync(:82),HasPendingMigrationsAsync(:88): schema lifecycle across every source the host uses. The contract states the asymmetry:EnsureCreatedAsyncskips sources with no configured connection string (:18-21), while the two migration members cover only the sources a migrations pipeline owns, which is every SQL Server source plus any SQLite or PostgreSQL source with a configuredSqliteMigrationsAssemblyorPostgreSQLMigrationsAssembly; Cosmos sources, and SQLite or PostgreSQL sources without a migrations assembly, are created byEnsureCreatedAsyncinstead (:74-81).SaveChangesAsync(:27) andSaveChanges(:32): save across all active contexts, the async overload documented as carrying audit stamping and domain-event dispatch.RequestExplicitKeyInsert(:40): a one-shot flag for the next save, signalling that it may include entities carrying explicit values for store-generated keys. The contract is engine-neutral (:34-39): each context's engine decides whether those inserts need a per-table toggle (its explicit-key insert dialect,IExplicitKeyInsertDialect), an engine with none saves unchanged, and the flag is cleared once the save completes (seeExplicitKeyInsertGroup).BeginTransaction/CommitTransaction/RollbackTransaction(:45,:50,:55): applied to every active context that supports transactions.ExecuteInTransactionAsync<TResult>(:70-72): the member handlers actually reach, running the operation under the active execution strategy so a retrying strategy retries the whole unit.
- Why it's built this way: the application layer already talks to
IUnitOfWork; this second interface exists so the physical-topology coordination (which databases, which transactions, which migrations) has a home that Infrastructure can implement and tests can mock, without leaking EF Core upward. - Where it's used: registered scoped as
DbContextFactory(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:110, throughTryAddScoped).UnitOfWorkdelegates its whole save and transaction surface to it (UnitOfWork.cs:85-94), the startup path resolves it to create, migrate, or verify databases (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:74,:242, and per tenant at:144), and the background and messaging paths resolve it per scope to reach a specific source (OutboxProcessoratOutboxProcessor.cs:202,OutboxCleanupService.cs:130,OutboxAdministration.cs:382,EfInboxStore.cs:34,InProcessEventBus.cs:52,BrokerEventBus.cs:33,ScheduledJobRunner.cs:231,AuditTrailReader.cs:35,AuditTrailCleanupJob.cs:46,EFRefreshSessionStore.cs:35, andRefreshSessionCleanupService.cs:125).
IPhysicalDbContextFactory
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/IPhysicalDbContextFactory.cs:15· Level 12 · interface
- What it is: the contract for constructing a raw context for a given physical data source. Its
doc comment states the split precisely: the engine selects the context class (SQL Server, Cosmos,
SQLite) and the source name selects the database (connection string, migrations assembly, EF model),
and contexts created here are neither scoped nor cached (
IPhysicalDbContextFactory.cs:6-13). - Depends on:
ApplicationDbContextas the return type,DataSourceKeyas the addressing type, andPhysicalDataSourceon the second overload (IPhysicalDbContextFactory.cs:22,:37). - Concept introduced, construction split from lifetime.
[Rubric §2, Design Patterns](assesses whether patterns are applied where they earn their keep): this is the Abstract Factory half of the pair. Deciding which class to new up for which database is a pure function of the key and needs no per-request state, so it lives in a singleton; deciding how long a context lives, when it saves, and what transaction it is in is per-request state and lives in the scopedIDbContextFactorylayered on top (IPhysicalDbContextFactory.cs:10-13). - Walkthrough: two members.
Create(DataSourceKey key)(IPhysicalDbContextFactory.cs:22) returns a new instance targeting the database the resolver maps that key to.Create(DataSourceKey key, PhysicalDataSource physicalDataSource)(IPhysicalDbContextFactory.cs:37) is the database-per-tenant overload: the caller clones the resolvedPhysicalDataSourcewith the tenant's connection string and passes the same key, so EF's model cache still serves one compiled model per (context type, source name) across every tenant (IPhysicalDbContextFactory.cs:24-35). - Why it's built this way: keeping the construction decision behind a two-method interface is what
makes the scoped coordinator testable without a database (
[Rubric §14, Testability]): the commit-ambiguity tests handDbContextFactoryaMock<IPhysicalDbContextFactory>that returns a SQLite in-memory context (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/DbContextFactoryCommitAmbiguityTests.cs:49-55). The two-overload shape is also what keeps tenancy (ADR-073) a routing decision in the scoped layer rather than a second factory. - Where it's used: registered singleton as
PhysicalDbContextFactory(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:111); injected intoDbContextFactory(DbContextFactory.cs:50), which calls both overloads at:94-96.
PhysicalDbContextFactory
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/PhysicalDbContextFactory.cs:19· Level 13 · class (sealed)
- What it is: the singleton implementation of
IPhysicalDbContextFactory. It resolves the key's connection information throughIDataSourceResolver(or accepts it from the caller) and asks the key's engine object to construct the matching context (PhysicalDbContextFactory.cs:25-33). - Depends on:
IServiceProvider,IDataSourceResolver, andIEntityConfigurationAssemblyProvider, all taken through a primary constructor (PhysicalDbContextFactory.cs:19-22), plusDataSourceEnginesand theIDataSourceEngineit returns, whoseCreateDbContext(IDataSourceEngine.cs:83) builds theSQLServerDbContext,PostgreSQLDbContext,SqliteDbContext, orCosmosDbContext. - Concept introduced, the never-pool rule.
[Rubric §8, Data Architecture]and[Rubric §12, Performance & Scalability](which assesses whether performance work is deliberate rather than reflexive): EF Core'sAddPooledDbContextFactoryis the standard way to avoid re-allocating contexts, and it is explicitly forbidden here. The class comment says why (PhysicalDbContextFactory.cs:13-17): each instance carries per-source constructor state (itsPhysicalDataSource), so a pool would hand a context configured for one database to a caller asking for another and silently point repositories at the wrong database. The same warning is repeated at the registration site (MMCA.Common.Infrastructure/DependencyInjection.cs:105-111), which is where someone optimizing DI would look first. Under database-per-tenant the rule is load-bearing twice over, since a pooled context could then cross a tenant boundary rather than only a module one. - Walkthrough:
- No options of its own: the static empty
DbContextOptions<T>objects now live one per engine class (for exampleSQLServerDataSourceEngine.cs:23,CosmosDataSourceEngine.cs:21), each built once and reused; provider, connection, interceptors, and model cache key are all set inside each context'sOnConfiguring, so those options exist only to satisfy theDbContextconstructor. Create(DataSourceKey key)(PhysicalDbContextFactory.cs:25): a one-liner that resolves thePhysicalDataSourcewithresolver.GetPhysical(key)and forwards to the two-argument overload, so the resolver path and the tenant path share one construction switch.Create(DataSourceKey key, PhysicalDataSource physicalDataSource)(PhysicalDbContextFactory.cs:28-33): null-guards the supplied source (:30), then returnsDataSourceEngines.For(key.Engine).CreateDbContext(serviceProvider, assemblyProvider, physical)(:32). The engine-to-class switch that used to live here is gone: each engine class constructs its own context with its own options.
- No options of its own: the static empty
- Why it's built this way: this is the single point where the two storage axes meet, the
Engineaxis of ADR-018 picking the class and theNameaxis of ADR-006 picking the database, so adding an engine is a new engine class plus a context class rather than a change anywhere in application code (ADR-130). Taking the connection information as a parameter is what let ADR-073 add a third, per-tenant axis without touching the switch. - Where it's used: registered singleton (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:111);DbContextFactory.GetDbContextcalls one overload or the other on every cache miss (DbContextFactory.cs:106-108), which is the only first-party call site.
IdentityModuleDbSeederBase<TUser>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Seeding·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeederBase.cs:54· Level 14 · class (abstract, partial)
- What it is: a
DbSeedersubclass that owns the whole per-account seeding idiom (normalize the email, skip if it exists, hash the password, build the aggregate, add, save) for an app-supplied list of development accounts. Its own summary records why it exists: that idiom was written out five times across the two apps' Identity modules and now lives here once (IdentityModuleDbSeederBase.cs:11-15). - Depends on:
IUnitOfWorkandIPasswordHasherand anILoggerthrough its primary constructor (:54-57; a protected two-argument overload at:68suppliesNullLogger.Instance, so a subclass that passes no logger still compiles, and both in-repo subclasses do exactly that),SeedAccountas the input record,Emailas the normalized value object,Result<T>as the factory-hook return type, andAuditableAggregateRootEntity<TIdentifierType>as theTUserconstraint (:58). The lost-race save is inherited fromDbSeeder(DbSeeder.SaveToleratingConcurrentSeedAsync), so this type does not touch the unique-constraint detectors or EF Core'sDbUpdateExceptionitself. - Concept introduced, the template method with app-specific hooks.
[Rubric §1, SOLID](assesses whether abstractions are open for extension and closed for modification, and whether subclasses vary only what genuinely differs) and[Rubric §15, Best Practices & Code Quality]: the base fixes the invariant sequence and leaves exactly two hooks beyond the account list, each for a reason the doc comment spells out (:18-26).CreateUserexists because the two apps'User.Createfactories take the same values in different parameter orders and only the app can name its own roles (compare ADC's ordering atMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:56-62with Store's atMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:51).EmailExistsAsyncexists because the existence predicate must be written against the app's concreteUserand never against an interface member, so EF translates it to the same SQL it did before the hoist. That second constraint is the one worth remembering: a predicate over an interface property is not translatable, so hoisting shared persistence logic into a generic base means leaving the query itself behind in the subclass. - Walkthrough:
- Constructor and protected state (
IdentityModuleDbSeederBase.cs:54-77): the primary constructor's parameters are null-guarded into protectedUnitOfWork(:74) andPasswordHasher(:77) properties, so subclasses can reach the unit of work for their existence predicate without taking it again, and into a private_logger(:60). The two-argument overload (:68-71) chains to the primary one withNullLogger.Instance. Accounts(:80): abstractIReadOnlyList<SeedAccount>, the ordered list the app supplies.SeedAsync(:82-89): the public entry point. It has no gate: it walksAccountsin order calling the private per-account routine (:85-88). Whether sample accounts are seeded at all is the caller's decision, made in the app'sIModuleSeederbefore it constructs and runs this seeder (:29-34).EmailExistsAsync(Email?, CancellationToken)(:99) andCreateUser(SeedAccount, byte[], byte[])(:108): the two abstract hooks. Their doc comments define the contract precisely, including thatemailisnullwhen the seed address failed validation, in which case no user can match it, and that a failedResultskips the account silently.SeedAccountAsync(:110-138): the idiom itself. Normalize throughEmail.Create(...).Valueso the EF predicate compares same-typed converted values (:113), ask the hook whether the account exists and return if so (:115-119), hash the plaintext password into a(hash, salt)pair (:121), call the app factory and unwrap its result withTryGetValue(out var user), returning silently on failure (:122-126), then resolve the repository throughIUnitOfWork.GetRepository<TUser, UserIdentifierType>()(:128), add the unwrappeduserdirectly, with no null-forgiving access (:129), and save through the inheritedSaveToleratingConcurrentSeedAsync(UnitOfWork, ...)(:131). When that returnsfalse(a unique or primary-key violation read as a lost insert race, with the failed save already discarded by the base), one information line is logged (:132-137) and seeding moves on to the next account. Any other failure still propagates out of the base helper.LogSeedAccountAlreadySeededConcurrently(:140-143): the source-generated[LoggerMessage]method atInformationlevel, which is why the type ispartial.
- Constructor and protected state (
- Why it's built this way: saving per account rather than once at the end is deliberate and is
stated in the class comment (
:33): one invalid account cannot roll back the others, which matches the pre-hoist behavior each app had. The per-account idiom is check-then-insert, so two replicas starting together on a database lacking an account both pass the existence check and both insert; the unique index on the email rejects the slower save, and the winner wrote the very account this run meant to write, which is why that rejection is absorbed rather than propagated (:36-43). The absorbing save itself lives onDbSeeder, so every seeder can use it, not only this one. Hashing goes throughIPasswordHasherrather than any local scheme, per ADR-032 (:76).[Rubric §11, Security]applies through the notice at:45-47: seed credentials are deliberately weak plaintext for local development, and a deployed environment must disable seeding or supply environment-sourced secrets. - Where it's used: subclassed once per app, by ADC's and Store's
IdentityModuleDbSeeder(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:27-30,MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:22), each of which is constructed and run by its module'sIModuleSeederat startup (ADC'sIdentityModuleSeederreadsSeeding:IncludeSampleUsersatMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:29, then constructs and runs the seeder at:35-36). Pinned byIdentityModuleDbSeederBaseTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/Seeding/IdentityModuleDbSeederBaseTests.cs:19,:28,:45,:56,:70,:84), which cover per-account add and save, normalization before the existence check, the skip-if-present path, the skip-on-factory-failure path, and the hashed credential reaching the app factory, plus the lost-unique-index-race path that seeds the next account (:101) and the other-failure path that still throws (:132). - Caveats / not-in-source: the type has no
ShouldSeedhook, so the configuration gate lives only in the caller. ADC's subclass says so explicitly (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:18) and the API-layerIdentityModuleSeederreads the flag before it constructs the seeder (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:29). A subclass that is constructed and run seeds every account it lists.
DbContextFactory
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:49· Level 11 · class (sealed)
- What it is: the scoped implementation of
IDbContextFactoryand the busiest type in this group. It caches oneApplicationDbContextper physicalDataSourceKeyfor the life of the scope, coordinates save, transaction, migration, and disposal across all of them, and is also the database-per-tenant routing point (DbContextFactory.cs:22-31). - Depends on:
IPhysicalDbContextFactory,IEntityDataSourceRegistry,IDataSourceResolver, andICurrentUserService, all null-guarded from the primary constructor into readonly fields (DbContextFactory.cs:66-69), plus three parameters read directly off the primary constructor:ITenantContext,IOptions<TenancySettings>(:54-55, with their contracts documented at:37-43), and an optionalICorrelationContext? correlationContext = null(:56, documented at:44-48), the scope's correlation id, captured onto every outbox row a context this factory creates writes; defaulted so a container that never registered one (a bare test provider) keeps the previous constructor shape and simply stores no correlation id. It also calls fourinternal staticmembers ofDomainEventSaveChangesInterceptor(BeginCaptureExclusion,EndCaptureExclusion,DropDeferred,FlushDeferredAsync, atDbContextFactory.cs:413,:447,:892, and:669) and the internalEnrolledCommandWake(Releaseat:507and:662,Dropat:893). - Concept introduced, coordinating one logical save across several physical databases.
[Rubric §8, Data Architecture](transaction boundaries, unit-of-work scope, per-service isolation) and[Rubric §12, Performance & Scalability](transactions handled once in a shared mechanism, never copy-pasted into handlers): every hard question raised by ADR-006 lands here. How many contexts does a request have (one per source it touches)? What does "commit" mean when there are two (sequential, best-effort, no two-phase commit)? When are in-process domain events allowed to run (only after a successful commit)? What happens when the commit itself fails with an unknown outcome (seeTransactionCommitAmbiguousException)? - Concept introduced, per-tenant routing without a second EF model.
[Rubric §11, Security]and[Rubric §30, Compliance, Privacy & Data Governance]: under ADR-073 a tenant may declare its own connection string for a source, and this class is where that declaration turns into a different database. The trick is that only the connection string changes: theDataSourceKeystays the same, which is what EF's model cache is keyed on, so one compiled model serves every tenant (DbContextFactory.cs:165-170). - Walkthrough:
- State (
DbContextFactory.cs:59-96):MaxSavePasses(3,:64);_dbContexts, the per-scopeDictionary<DataSourceKey, ApplicationDbContext>that guarantees every repository in a scope shares one change tracker per database (:74);_routedContextTenants, recording which tenant each per-tenant-routed context was created for and holding only overridden sources (:76-81);_transactionActive(:87); the one-shot_explicitKeyInsertRequestedflag (:94); and avolatile bool _disposed(:96). GetDbContext(DataSourceKey)(DbContextFactory.cs:99-133): throws if disposed (:101), then on a cache miss asksResolveTenantOverridefor the tenant's own connection information and creates the context through whicheverCreateoverload applies (:105-108), records the creating tenant when the source was routed (:112-113), attaches the scope's accessors (:115), and enlists the new context in an already-active transaction (:119-120), so a source first touched inside a transactional command still shares the boundary. On a cache hit it callsGuardRoutedTenantUnchanged(:125) and thenGuardSharedContextNotRoutable(:129).AttachScopeAccessors(DbContextFactory.cs:147-163): hands the context three delegates rather than copied values, because a context can be created before the request's tenant or principal is resolved and both the query filter and the outbox capture must read the answer that holds at query and save time rather than at construction time. It setscontext.TenantIdAccessor = () => tenantContext.TenantId(:152),context.AllTenantsAccessor = () => tenantContext.IsAllTenants(:153), which backsApplicationDbContext.IsAllTenantsScope, the flag that lets a scope declared an all-tenants system scope read every tenant's rows instead of having theTenantquery filter hide them (ApplicationDbContext.cs:159-166), andcontext.OutboxOriginAccessor = () => new OutboxOrigin(_currentUserService.UserId, AmbientOrigin.FlattenRoles(_currentUserService.Roles), AmbientOrigin.FlattenPermissions(_currentUserService.User), tenantContext.TenantId, correlationContext?.CorrelationId)(:157-162, permissions passed positionally at:160), so the captured origin carries the caller's flattened permission claims alongside the roles. The origin delegate is invoked once per save that writes outbox rows, not once per row, so flattening the claims costs one pass per save (:155-156). It null-guards inside rather than at the call site so the null tolerance a mocked physical factory needs does not leak a maybe-null flow state back into the caller.ResolveTenantOverride(DbContextFactory.cs:171-196): returnsnull(source stays shared) unless there is a tenant, bound settings, an entry for that tenant, and an entry for this source name (:173-179); otherwise it takes the engine-appropriate connection string throughTenancySettingsValidator.ConnectionStringFor(:181), still returningnullwhen the tenant overrides only a different engine (:182-186), and finally clones the sharedPhysicalDataSourcewith the tenant's connection string and Cosmos database name (:188-195).GuardRoutedTenantUnchanged(DbContextFactory.cs:204-221): if the cached context was routed for a tenant and the scope's tenant has since changed, it throws with both tenant ids named (:213-220). The doc comment states the stakes (:198-203): serving that context to a second tenant would read and write the first tenant's data under the second tenant's filter value.GuardSharedContextNotRoutable(DbContextFactory.cs:229-240): the mirror-image guard. A context created shared (because a repository call ran before the tenant resolved) is refused once the scope's tenant turns out to override that source: unless the context was itself routed orResolveTenantOverridenow returnsnull(:231), it throws anInvalidOperationExceptiontelling the caller to resolve the tenant before the first repository call or use a fresh scope. Serving it would read and write the shared database for a tenant that owns its own.GetSourcesInUse(DbContextFactory.cs:260-261): the union of every source backing a registered entity (fromIEntityDataSourceRegistry) and every source already materialized in this scope, which is whatEnsureCreatedAsync(:243-254) andGetMigrationTargets(:844-857) iterate.EnsureCreatedAsyncskips sources with an empty connection string (:249-250).GetMigrationTargets(DbContextFactory.cs:844-857): the shared filter behindMigrateAsync(:824-828) andHasPendingMigrationsAsync(:860-869). It keeps a source only when its resolvedPhysicalDataSource.IsMigrationTargetis true (:850): every SQL Server source, plus a SQLite or PostgreSQL source with a configured migrations assembly. The doc comment (:830-842) records the deliberate asymmetry that property carries: a migration target with no connection string is skipped unless its engine requires one, so an optional SQLite source a test host leaves unconfigured stays silently absent, while a SQL Server source with no connection string still fails loudly at startup, because for SQL Server that is a misconfiguration rather than an option.SaveChangesAsync(DbContextFactory.cs:273-321): reads and immediately clears the explicit-key-insert flag (:275-276), then loops at mostMaxSavePassestimes over the contexts it has not yet saved (:285-299), passing_currentUserService.UserIdinto each context's audit-awareSaveChangesAsyncoverload (:297). The re-loop exists because saving dispatches domain events in-process, and a handler that resolves a repository for a source nobody had touched yet callsGetDbContextmid-enumeration (:281-284). After the loop it asserts that no cached context still has changes and throws anInvalidOperationExceptionnaming the offending sources if any does (:307-318), because anything still tracked when the unit of work returns would be silently lost. The comment at:301-306explains why the assertion reads the change tracker rather than the saved set: it must catch both a context materialized past the pass bound and a handler that dirtied an already-saved context.SaveChanges(DbContextFactory.cs:476-484): the synchronous path, a single pass over a snapshot of the cached contexts with no re-loop.- Explicit-key insert path (
DbContextFactory.cs:295-296,:332-473): a context takes it only when the flag is set ANDcontext.Engine.ExplicitKeyInsertreturns anIExplicitKeyInsertDialect(SQL Server'sSET IDENTITY_INSERT); every other engine saves normally.SaveWithExplicitKeyInsertAsync(:332) asks the dialect for theExplicitKeyInsertGroups and opens the connection itself when it is not already open, because the toggle is session state and without an ambient transaction EF would otherwise return the connection to the pool between the toggle and theINSERT; an already-open connection is left as found (:351-361).SaveExplicitKeyGroupsAsync(:386) then saves one table per round with the toggle SQL built bydialect.BuildToggleSql, each round inside aBeginCaptureExclusion/EndCaptureExclusionpair (:413,:447); a comment beside the toggle (:422) records that the schema and table identifiers come from EF model metadata, never user input. The toggle-off SQL is built once per round (:427); on a successful save it runs unconditionally withCancellationToken.None(:442), but on a failed save it goes throughTryToggleOffAsync(:438, defined at:461), which is best-effort, and the original exception is rethrown. The reason is that the session may already be gone (the same fault that failed the save), and a throw from the toggle-off would replace the save's real exception and hide a transient error from the execution strategy. Before saving, the groups are reordered byExplicitKeyInsertRoundOrder.Order(:344), because the change tracker's order is the order rows were added and says nothing about foreign keys; the result is one round per table, principals first. BeginTransaction/CommitTransaction/RollbackTransaction(DbContextFactory.cs:486-521): each filters to contexts that support transactions and, symmetrically, to those that do or do not already carry one (:494,:501,:513), because EF throws on a secondBeginTransactionfor the same connection andGetDbContextmay already have enlisted a late-created context (:490-493). Commit snapshots the committed contexts and then callsEnrolledCommandWake.Releaseon them (:501-507): internal commands enrolled during the transaction are durable only now, so this is the first moment waking the processor finds them. Rollback additionally callsDropDeferredWorkon every context (:519-520), which drops both the deferred in-process dispatch (DomainEventSaveChangesInterceptor.DropDeferred) and the owed processor wake (EnrolledCommandWake.Drop,:890-894): the aggregate changes and their outbox rows just rolled back, so neither may run, and neither must survive into a retry.ExecuteInTransactionAsync<TResult>(DbContextFactory.cs:579-624): re-entrancy first, a nested call simply runs the operation on the ambient transaction (:590-591), because an inner commit would make the outer scope's earlier work durable ahead of its own decision (:583-589). Otherwise it picks the execution strategy from the first transaction-capable context, materializing theDefaultsource through the resolver if none exists yet (:599-600, deliberately resolved rather than taken literally so a host with no SQL Server connection does not open a connection string that does not exist,:593-598), and runs the attempt understrategy.ExecuteAsync(:606-614), callingResetForRetrybefore every attempt after the first (:608-609). A commit failure the attempt returned is thrown only after the strategy has finished (:620-621), because the strategy judges retriability by walking an exception's whole inner chain (:616-619). The method's remarks then hand recovery to the caller with an explicit warning (:557-566): verify before any resend, because an[Idempotent]request does NOT replay safely (its record is stored only for a 2xx), the API answers with the coded 500 ofCommitOutcomeUnknown, and the outbox delivers whatever the commit did make durable (:562-565).RunTransactionalAttemptAsync(DbContextFactory.cs:634-684): one attempt, begin to commit. A failedResultrolls back and returns (:643-650), which is what makes ADR-013's Result-over-exceptions rule safe for partial persistence. On success it first runsFlushEnrolledCommandsBeforeCommitAsync(:653), then commits throughTryCommit(:655-657), and only then flushes the deferred dispatch on every context, snapshotting the dictionary first because a handler can still materialize a new source (:664-671). Between the commit and that flush it releases the internal-command wake for every context (EnrolledCommandWake.Release,:662), deliberately before the event flush so a throwing in-process handler cannot swallow it. Any exception, cancellation included, goes throughRollbackBestEffortand is rethrown (:675-682); that helper (:691-705) swallows a failing rollback, clears the transaction flag and drops every context's deferred work by hand, so the rollback error never replaces the original exception the execution strategy must judge.FlushEnrolledCommandsBeforeCommitAsync(DbContextFactory.cs:717-743): applies the commit rule to whatever the operation left tracked but unsaved. An internal command scheduled while the transaction is open is only enrolled on the context, so when every pending entry is an addedInternalCommandMessagethe unit is saved here, inside the transaction (:742), and the row commits with the rest. Any other unsaved change throws anInvalidOperationExceptionnaming the source, entity type and state (:734-740), because committing would silently discard it while the unit reports success.TryCommit(DbContextFactory.cs:755-789) andAbandonAfterCommitFailure(:798-821): a commit failure is returned, not thrown (:782).TryCommitsnapshots the enlisted contexts first, because that order is the commit order (:759-764), then commits them one by one, accumulating the successes; on a throw it names the failing source, treats everything past it in the snapshot as rolled back (:780), and hands all three groups toTransactionCommitAmbiguousException.AbandonAfterCommitFailuredrops every deferred dispatch and owed wake (DropDeferredWork,:804), rolls back whatever has not committed yet, and swallows secondary rollback failures so the commit ambiguity stays the reported failure (:809-819).ResetForRetry(DbContextFactory.cs:876-883): before the strategy re-runs the operation it drops deferred work (DropDeferredWork,:880: dispatch and the owed wake) and callsChangeTracker.Clear()on every context (:881), so entities the aborted attempt added are not inserted a second time (with a duplicate outbox row per event).SupportsTransactions(DbContextFactory.cs:900-901):context.Engine.Capabilities.IsRelational, so the Cosmos "no multi-document transactions" fact is read off the engine object rather than a type test;HasActiveTransaction(:903-904) isDatabase.CurrentTransaction is not null.- Disposal (
DbContextFactory.cs:906-936):DisposeandDisposeAsyncboth dispose every cached context, clear the dictionary, set_disposed, and suppress finalization.
- State (
- Why it's built this way: ADR-006
makes "one scope, several databases" the normal case, so somebody has to own the cross-context
bookkeeping; putting it here keeps handlers writing
SaveChangesAsyncexactly as they would against a single database, and ADR-073 then reuses that one chokepoint for per-tenant routing. The subtleties (bounded re-loop plus the unsaved assertion, the pre-commit check on unsaved changes, deferred dispatch released only after commit, a commit failure exempted from retry and reported per source, the routed-tenant guards, and the re-entrancy short circuit) are each a correctness fix with the reasoning written into the source next to the code. - Where it's used: registered scoped as
IDbContextFactory(TryAddScopedatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:110) and consumed through that interface everywhere (see the interface's section). Directly instantiated in tests, for exampleMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/DbContextFactoryCommitAmbiguityTests.cs:55and:220; the save-loop invariants are pinned byDbContextFactorySaveIntegrityTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DbContexts/DbContextFactorySaveIntegrityTests.cs:82,:104,:123), which assert that a handler mutating an already-saved context throws naming that context, that an extra read-only context does not, and that a clean scope returns the written count. - Caveats / not-in-source: the
MaxSavePassesbound of 3 is documented as "two passes cover the realistic case, the third is slack" (DbContextFactory.cs:59-63); whether any production workload has ever needed the third pass is Not determinable from source. The routed-tenant guard also implies a usage rule the code can only enforce after the fact: a scope serves one tenant, and switching tenants means a fresh scope (:213-220).
InternalCommandOrigin
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandOrigin.cs:21· Level 0 · record struct (internal, readonly)
- What it is: the eight-field snapshot of the scheduling context a deferred
InternalCommandMessageneeds to restore around its later execution: the user id, a flattened roles string, a JSON array of permission claims, the tenant id, the correlation, trace and span ids, and the W3C trace flags that carry the scheduling request's sampling decision (InternalCommandOrigin.cs:21-29,TraceFlagsdocumented at:17-20). - Depends on:
UserIdentifierType;TraceFlagsis a nullablebyte(null when no activity was current); every other member is a plain nullablestring. - Concept introduced: none new. It plays the same role for the internal-command queue that the
outbox's own ambient-context capture (
OutboxOrigin.cs) plays for events: a value type that carries exactly what a disconnected, later execution needs to look like the scope that scheduled it. - Walkthrough: a plain positional
internal readonly record structwith no members beyond its eight constructor parameters. Value semantics are what let it be captured once byInternalCommandOriginCapture.Captureand copied cheaply onto the row. - Why it's built this way: a
record structrather than aclassbecause it is a short-lived value with no identity of its own, constructed once per scheduled command and read once when the row is built;internalbecause only this project's scheduling and message types touch it. - Where it's used: built by
InternalCommandOriginCapture.Capture(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandOriginCapture.cs:28-41), whichInternalCommandSchedulercalls while building the row (InternalCommandScheduler.cs:85), and consumed byInternalCommandMessage.FromCommand, which copies all eight fields onto the row (InternalCommandMessage.cs:176-183). Pinned byInternalCommandTraceFlagsTestsandInternalCommandOriginWithheldRoleTests, and constructed directly inInternalCommandLaneProcessorTests(all underMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/).
CrossTenantWriteException
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/CrossTenantWriteException.cs:25· Level 0 · class (sealed, exception)
- What it is: the single failure type of the write side of multi-tenancy. It is thrown when a
save would insert, update or delete a row owned by a tenant other than the one the current scope
resolved, would insert an untenanted row from a scope that resolved no tenant at all, or would
write a tenanted row from a scope that resolved no tenant and is not an all-tenants system scope
(
CrossTenantWriteException.cs:5-10). - Depends on: the BCL only (
InvalidOperationException,string.FormatwithCultureInfo.InvariantCulture). It is thrown exclusively byTenantSaveChangesInterceptor; it does not reference it. - Concept introduced, why isolation fails loudly on the write side and silently on the read side.
[Rubric §11, Security]assesses whether authorization boundaries are enforced by construction rather than by caller discipline, and[Rubric §30, Compliance and Data Governance]assesses whether tenant data separation is demonstrable. Read isolation is a query filter, and a filter that disagrees with the caller simply returns nothing: a wrong tenant sees an empty list, which is the correct and harmless outcome. A save has no equivalent harmless outcome. By the time the interceptor sees the entry, the row is about to be written, and the only honest results are "the correct tenant" or "no write at all", so this type throws instead of filtering (CrossTenantWriteException.cs:13-18). The message names the entity type and both tenants because the realistic cause is a scope that was never given a tenant (a background job, a queued handler) rather than a genuine attempt to cross the boundary. - Walkthrough:
DefaultMessage(:27-28): the parameterless-constructor text, "The save would write across the tenant boundary and was rejected."- The three public constructors (
:31-32,:36-37,:42-43): parameterless, message, and message-plus-inner. They exist so the type satisfies the standard exception shape the analyzers require, even though the framework itself never calls them. - The private constructor (
:45-55): the one the factories use. It takes the formatted message plus the three diagnostic values and assigns them to the properties. EntityType,CurrentTenantId,EntityTenantId(:58,:63,:69): allstring?, all get-only. A catch site can branch on the data instead of parsing the message.CurrentTenantIdis null exactly when the scope resolved no tenant;EntityTenantIdis null when the entity carried none.ForMismatch(entityType, operation, currentTenantId, entityTenantId)(:79-95): builds the "the entity belongs to tenant X but this scope resolved tenant Y" message.operationis the literalinsert,updateordeletepassed by the interceptor, so one factory covers all three write shapes.ForUnscopedWrite(entityType, operation, entityTenantId)(:105-120): builds the message for a write of a tenanted row from a scope that resolved no tenant and was not declared an all-tenants system scope. It names the two ways out: resolve the tenant for the scope viaITenantContext.SetTenant, or declare a system operation withITenantContext.SetAllTenants().CurrentTenantIdis passed as null;EntityTenantIdcarries the tenant the row names. LikeForMismatchit takes the operation, so it covers inserts, updates and deletes.ForUnresolvedTenant(entityType)(:127-137): builds the message for the remaining failure, an untenanted insert from an untenanted scope, and names the two ways out in the message itself: resolve a tenant for the scope viaITenantContext.SetTenant, or assign the tenant on the entity before saving. Both tenant ids are passed as null.
- Why it's built this way: it derives from
InvalidOperationException(:21-22,:25) so existing handler and middleware catch sites treat it exactly as they treat the framework's other save-time invariant failures, with no new catch clause anywhere. All three factories areinternal, which keeps the interceptor the only thing that can produce a populated instance while leaving the type public for consumers to catch. See ADR-073 for the multi-tenancy model this enforces. - Where it's used: thrown at five call sites in
TenantSaveChangesInterceptor(TenantSaveChangesInterceptor.cs:126for the unresolved-tenant insert,:132for a tenanted insert from an unscoped scope,:142for a mismatched insert,:166for an unscoped update or delete,:180-181for a mismatched update or delete); asserted byTenantSaveChangesInterceptorTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Tenancy/TenantSaveChangesInterceptorTests.cs:12, with the unresolved-tenant case at:34, the unscoped insert, update and delete at:60,:75and:92, the mismatched insert at:122, and the mismatched update and delete at:136and:153). It also surfaces through the API'sGlobalExceptionHandler(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/GlobalExceptionHandler.cs, 2 references).
LocalLease
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:502· Level 0 · record struct (private readonly, nested)
- What it is: a two-field value,
Until(aDateTime) andToken(aGuid), describing the lease one save's in-process outbox rows are inserted under (DomainEventSaveChangesInterceptor.cs:499-502).Untilis when the lease expires and pollers may take the rows;Tokenis what the release after a failed dispatch is guarded by. - Depends on: nothing beyond the BCL (
DateTime,Guid). It is whereCapturedStategets itsLocalLeaseTokenfrom, and the argumentDomainEventSaveChangesInterceptorhands toCaptureEventsAndPersistToOutbox(:248). - Concept introduced, a lease is a deadline plus an identity.
[Rubric §29, Resilience and Business Continuity]assesses whether a replica that dies mid-work leaves recoverable state. A local event's outbox row is written, then dispatched in-process, then stamped processed. In a multi-replica host another replica'sOutboxProcessorcould poll the row in the gap and deliver the event a second time. The lease closes that gap: the row is inserted already locked untilUntil(:343-344), so every poller skips it while this process handles the event. TheTokenmakes the later release safe, because it clears the lock only on rows still carrying this save's token (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxFinalizer.cs:79), never a row a processor has since claimed under its own. - Walkthrough:
- Creation (
NewLocalLease,:348-349):Untilis the injectedTimeProvidernow plus_localLeaseSeconds(:71), read once fromOutbox:LeaseSeconds(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxSettings.cs:100, default 300);Tokenis a freshGuid.NewGuid(). - Application (
ApplyLocalLease,:338-345): copies the pair ontoOutboxMessage.LockedUntilandLockToken. A null lease returns without touching the row. - Absence (
:117): the synchronousSavingChangespasseslocalLease: null, because that path never dispatches in-process, so its rows belong to the processor from the start.
- Creation (
- Why it's built this way: a
readonly record structis a value that lives for one capture and is never stored on the singleton interceptor, which keeps the singleton free of per-save state.privatekeeps the lease an implementation detail; the only trace that outlives the capture is theToken, copied intoCapturedState. - Where it's used: created per async save (
:104), threaded throughCaptureEventsAndPersistToOutbox(:248,:301,:320), and deliberately not applied to integration-event rows, which nothing in-process delivers (:295-304).
EnrolledCommandWake
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/EnrolledCommandWake.cs:14· Level 1 · class (internal, static)
- What it is: a static ledger of processor wakes that are owed to a transaction which has not committed yet: a row enrolled in an open transaction cannot be signalled at once, so the wake is recorded here and released only after the commit succeeds (
EnrolledCommandWake.cs:14-54). - Depends on:
IInternalCommandSignal(the wake being deferred), EF CoreDbContext(the key), BCLConditionalWeakTable. - Concept introduced, a commit-gated wake.
[Rubric §6, CQRS and Event-Driven]assesses whether deferred work is delivered reliably: signalling the processor before the commit would only buy a query against a row that is not visible yet, and never signalling would leave the row waiting for the fallback poll. The ledger sits between the two:Deferrecords the debt,Releasepays it after commit,Dropcancels it on rollback. - Walkthrough:
Owed(EnrolledCommandWake.cs:16) is aConditionalWeakTable<DbContext, IInternalCommandSignal>, so an entry never keeps an abandoned context alive;Defer(context, signal)(EnrolledCommandWake.cs:21-22) is anAddOrUpdatekeyed by the context that holds the enrolled row;Release(committedContexts)(EnrolledCommandWake.cs:30-49) collects the signal owed by each committed context, removes the entry, de-duplicates by signal instance, then callsSignal()once per distinct signal, so many rows or contexts produce one wake;Drop(context)(EnrolledCommandWake.cs:53) forgets the entry because the transaction did not commit. - Why it's built this way: keying by context ties the debt to the exact transaction that holds the row, and the weak table means the rollback and abandoned-context paths cannot leak. The doc comment on
Releasesays to call it only after every commit succeeded (EnrolledCommandWake.cs:24-28). - Where it's used:
InternalCommandSchedulercallsDeferwhen it enrolls a row in an open transaction (InternalCommandScheduler.cs:114, seeInternalCommandScheduler);DbContextFactorycallsReleaseafter commits (DbContextFactory.cs:507,DbContextFactory.cs:662) andDropon the rollback path (DbContextFactory.cs:893). - ADRs: ADR-107, ADR-114.
AggregateCapture
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:482· Level 2 · record (private sealed, nested)
- What it is: a two-field pairing of one tracked aggregate root and the exact array of domain
events snapshotted from it for the current save
(
DomainEventSaveChangesInterceptor.cs:479-484). - Depends on: EF Core's
EntityEntry<IAggregateRoot>andIDomainEventviaIAggregateRoot. - Concept introduced, snapshot-then-remove instead of clear. The naive move after dispatching
events is
entity.ClearDomainEvents(). That is wrong here, and this record is the fix. An in-process handler running during dispatch can raise a new event on the same aggregate; a wholesale clear would wipe that new event before any later capture could see it, so it would never dispatch and never reach the outbox. Holding the exact snapshot lets the interceptor remove precisely what it captured and leave everything else in place (DomainEventSaveChangesInterceptor.cs:464-474). - Walkthrough:
Entry(:468): theEntityEntry<IAggregateRoot>, not the bare entity. Keeping the entry means the record still has EF's view of the aggregate available if the flush path ever needs it, andcapture.Entry.Entityreaches the aggregate itself (:458).Events(:469): anIDomainEvent[]materialized with a collection expression at capture time (:250,[.. e.Entity.DomainEvents]), which is what makes it a snapshot rather than a live view of the aggregate's mutable list.
- Why it's built this way: a positional
recordgives value semantics and an immutable pair for free, andprivate sealedkeeps it invisible outside the interceptor. It is data, not behavior: the only method that touches it isRemoveCapturedEvents, which callscapture.Entry.Entity.RemoveDomainEvents(capture.Events)on each (:457-458, against the contract member atMMCA.Common/Source/Core/MMCA.Common.Domain/Interfaces/IAggregateRoot.cs:35). - Where it's used: constructed once per event-carrying aggregate in
CaptureEventsAndPersistToOutbox(:247-251), stored insideCapturedState(:478), and consumed byRemoveCapturedEvents(:455-459).
OwnedDependents
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/OwnedDependents.cs:12· Level 2 · class (internal, static)
- What it is: a single-purpose helper that answers one question about a tracked owner entry:
is any owned reference or owned collection item of it being inserted, updated or deleted in this
save? (
OwnedDependents.cs:14-26). - Depends on: EF Core's
EntityEntry,ReferenceEntry,CollectionEntryandEntityStateonly. No MMCA types. - Concept introduced, an owner can look Unchanged while its row is being rewritten. EF tracks an
edit inside an owned value object (an
OwnsOneaddress, anOwnsMoneyamount) on the owned entry and leaves the owner's own stateUnchanged, even though the owned columns live in the owner's table and the row is updated. Any interceptor that decides fromentry.Statealone therefore misses the update.[Rubric §8, Data Architecture]assesses whether audit guarantees hold at the schema level, and this is the case that breaks "every row knows who wrote it and when" for value-object edits. - Walkthrough:
HaveChanges(:24-26): true when any reference navigation passesIsChangedOwnedReferenceor any collection navigation passesHasChangedOwnedItem.IsChangedOwnedReference(:29-31): the navigation must target an owned type (Metadata.TargetEntityType.IsOwned()) and itsTargetEntrymust beAdded,ModifiedorDeleted.HasChangedOwnedItem(:34-37): the collection must target an owned type, and any non-null item whosecontext.Entry(item).Statediffers fromUnchangedcounts.- Known blind spot (
:18-21): an optional owned reference set tonullleaves no target entry to read, so clearing one is not detected; replacing or editing one is.
- Why it's built this way: one shared walk keeps the two interceptors that need it from drifting
into two slightly different definitions of "the owner changed". It is
internal staticbecause it is plumbing between sibling interceptors, not a public extension point. - Where it's used:
AuditSaveChangesInterceptorpromotes an Unchanged owner with owned changes toModifiedbefore stamping (AuditSaveChangesInterceptor.cs:73), andAuditTrailSaveChangesInterceptortreats such an entry as auditable (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailSaveChangesInterceptor.cs:276).
CapturedState
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:492· Level 10 · record (private sealed, nested)
- What it is: the whole of what
DomainEventSaveChangesInterceptorlearns before a save and needs again after it: which aggregates it captured, which events it will dispatch in process, which outbox rows back those events, whether any integration events are in the batch, and the token the local rows were leased under (DomainEventSaveChangesInterceptor.cs:486-497). - Depends on:
AggregateCapture,IDomainEvent,OutboxMessage; its lease token comes fromLocalLease. - Concept introduced, why per-save state cannot live in a field. The interceptor is registered
as a singleton (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:67), and one singleton serves every context in every scope concurrently. Anything it remembers betweenSavingChangesandSavedChangestherefore has to be keyed by the context, not stored on the instance. That is exactly what this record is: the value side of aConditionalWeakTable<DbContext, CapturedState>(:73).[Rubric §12, Performance and Scalability]assesses whether shared components stay safe and cheap under concurrency; the weak table adds no lock and no lifetime bookkeeping, because an entry disappears when its context is collected. - Walkthrough (all five members are positional and immutable):
Captures(:456): theAggregateCapture[], used only to remove exactly the captured events afterwards.LocalEvents(:457): the events that get in-process dispatch. On a context that writes outbox rows this deliberately excludes everyIIntegrationEvent(:270-283); on a context without outbox support, or in a host that turned the outbox off, it is simply every captured event (:297).LocalOutboxEntries(:458): theList<OutboxMessage>rows backingLocalEvents, in the same order they were added. After a successful dispatch these are the rows stamped processed (:378); after a failed one they are the rows whose lease is released (:415).HasIntegrationEvents(:459): a bool rather than a second list, because integration events are never dispatched here. The only thing the flush needs to know is whether to wake the outbox processor (:380-381).LocalLeaseToken(:460): a nullableGuid, the tokenLocalOutboxEntrieswere leased under. It is null when the rows were inserted unleased (the synchronous path,:111), andReleaseLocalLeaseAsyncreturns early on null (:410).
- Why it's built this way: splitting local events from integration events at capture time,
and recording the split in this one value, is what makes
AddDomainEvent(integrationEvent)broker-correct (ADR-003). Before this routing existed, an integration event was dispatched locally and its row marked processed, so it silently never reached the wire (:24-29). Carrying only the lease token, not the whole lease, is enough: the expiry is already on the rows, and the token is all the guarded release needs. - Where it's used: created at the end of
CaptureEventsAndPersistToOutbox(:300-301), read byDispatchAndFinalizeAsync(:348), carried across a commit boundary inside the post-commit closure handed toDeferUntilCommit(:391), consumed byFlushStateAsync(:369-399) andReleaseLocalLeaseAsync(:408-422), and read on the synchronous path bySavedChanges(:141-149).
InternalCommandMessage
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandMessage.cs:20· Level 4 · class (sealed)
- What it is: the durable row of the internal-command queue: one
InternalCommandstable entry per scheduled deferred command, carrying its serialized payload, its execution state (attempts, lease, dead-letter instant), and the scheduling context to restore when it finally runs (InternalCommandMessage.cs:20-241). - Depends on:
InternalCommandOrigin(the constructor argument toFromCommand),IInternalCommandandInternalCommandNameResolver(both resolve/store the command identity),InternalCommandNameAttribute(named in the doc comments as the alternate identity a command can declare),UserIdentifierType, andSystem.Text.Json(JsonSerializer, and aJsonSerializerOptionsleft at its defaults,:22-32). BCL:ConcurrentDictionary<string, Type?>. - Concept introduced, a job-queue row is the outbox's row shape, generalized.
[Rubric §6, CQRS and Event-Driven]assesses whether deferred and asynchronous work is delivered reliably, and this type is why: the comment insideResolveCommandType(:225-227) states the ordering is "load-bearing, exactly as inOutboxMessage", and the two rows share the same two-tier type-resolution idea (an explicit stored name first, a reflection scan second, a success cached) because both are the same problem: a JSON payload written under one deployed assembly must still resolve after a rename or a redeploy. The difference from the outbox is the extra columns this row carries that an outbox row does not:Attempts,LastError,DeadLetteredOn,ClaimedBy,ClaimedUntil. Those are what turn "persist then publish" into "persist, lease, retry with backoff, dead-letter", the durable job queue taught in ADR-114. - Walkthrough:
SerializerOptions(:32):new(), theSystem.Text.Jsondefaults, deliberately the same asOutboxMessage(:22-31). Default reference handling refuses a reference cycle in a command with aJsonExceptionat schedule time, inside the caller's transaction.CommandTypeCache(:42): astatic ConcurrentDictionary<string, Type?>keyed by the stored name,StringComparer.Ordinal. Only a successful resolution is cached, consistent withOutboxMessage(:34-41); here that is defensive rather than load-bearing, because the processor dead-letters a row whose type it cannot resolve on its first attempt (type_unresolvable), so an unresolvable name costs one assembly scan per row and is never retried.Id(:45):Guid, defaulted withGuid.NewGuid()at declaration, so a caller never has to supply one.CommandType(:52) andPayload(:55): bothrequired string.CommandTypeis the stored identity used to resolve the CLR type back on deserialization, either theInternalCommandNameAttributename or the assembly-qualified type name (:47-51);Payloadis the JSON body.ScheduledOn/CreatedOn(:61,:64): the earliest UTC instant the command may run, and the UTC instant the row was written; equal for an immediate schedule.ProcessedOn,Attempts,LastError,DeadLetteredOn,ClaimedBy,ClaimedUntil(:70,:73,:80,:87,:94,:102): the processor's execution state.LastErrorrecords everyResulterror the handler returned (code and message), or the exception message followed by its causes, truncated to the column width (:75-79).ClaimedBy/ClaimedUntilcarry the lease: a claiming replica stamps the outcome only on a row still carrying its own token, so a replica whose lease expired mid-execution cannot overwrite the row a different replica already took over (:89-93); the sameClaimedUntilcolumn doubles as the retry backoff, a failed attempt re-leasing the row for the computed wait (:96-101).DeadLetteredOnmarks a row abandoned afterInternalCommands:MaxAttempts, requeued only throughApplication.InternalCommands.IInternalCommandAdministration(:82-86).CorrelationId,TraceId,SpanId,TraceFlags,UserId,UserRoles,UserPermissions,TenantId(:108,:111,:114,:123,:130,:137,:145,:151): the restorable half ofInternalCommandOrigin, copied onto the row rather than referenced (UserPermissionsis a JSON array of strings, unbounded and never truncated, restored aspermissionclaims so a command granted only through a claim passes the same gate deferred,:139-144), so the scheduling context survives independently of the struct that captured it.TraceFlags(byte?) is the scheduling request's sampling decision: the processor rebuilds the parent trace context with these flags, so a parent-based sampler exports the execution span only when the scheduling request was sampled, and a null (no ambient activity, or a row written before the column existed) reads as not sampled (:116-122).FromCommand(command, scheduledOn, createdOn, context)(:161-185,internal static): null-guards the command (:167), resolves its stored identity viaInternalCommandNameResolver.GetStorageNameand serializes it withSerializerOptions(:172-173), then copies every field of the passed-inInternalCommandOriginonto the new row (:176-183, eight fields includingUserPermissionsandTraceFlags).DeserializeCommand()(:197-204,internal): resolves the type throughResolveCommandType, returnsnullif unresolvable, otherwise deserializesPayloadas that type.ResolveCommandType()(:218-235,private): returns a cache hit fromCommandTypeCache(:220-223); on a miss,Type.GetTypeis tried first andInternalCommandNameResolver.FindTypeByDeclaredNameis the fallback, in that order on purpose (:225-228). A null result, or a type not assignable toIInternalCommand, returnsnullwithout caching, exactly asOutboxMessageaccepts only an event type, so a stored name naming any other type is never materialized (:230-236); only a valid internal command type is written back to the cache (:238).IsCommandTypeCached(storedName)(:209,internal static): a test hook reporting whether a stored name currently has a cached resolution.
- Why it's built this way: the serializer options are the
System.Text.Jsondefaults on purpose (:22-32). A reference cycle in a command is a modelling error (in practice an entity graph put on the payload), so it should fail loudly: the default reference handling throws aJsonExceptionat schedule time, inside the caller's transaction, where ignoring the cycle would have written the back-reference asnulland later run a command that was not the one scheduled. The usual cause is caught earlier still, at build time, by the architecture ruleArchitectureRules.InternalCommandPayloadsHoldNoEntities(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Contracts/ArchitectureRules.InternalCommandPayloads.cs:26, run byEventConventionTestsBase.cs:41). Rows written under the earlier cycle-ignoring options carry no reference metadata, so they still read back (:29-30). The two-tier name resolution mirrorsOutboxMessagedeliberately (:225-227), so a reviewer who has read one already understands the other. - Where it's used: added to the caller's
IDbContextFactorycontext byInternalCommandScheduler.ScheduleAsync(InternalCommandScheduler.cs:104-105), so it commits atomically with the caller's aggregate change inside a transaction, or saves immediately outside one; claimed, executed and stamped byInternalCommandProcessor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs, 17 references) andInternalCommandLaneProcessor(Processing/InternalCommandLaneProcessor.cs, 9 references); mapped byApplicationDbContextas oneInternalCommandstable per relational source (ApplicationDbContext.cs, 6 references); administered byInternalCommandAdministrationand swept byInternalCommandCleanupService. Pinned byInternalCommandModelTests,InternalCommandSchedulerTests,InternalCommandProcessorTestsandInternalCommandAdministrationTestsinMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/. - Caveats / not-in-source: the mapped
UserRolescolumn has a documented width (MaxRolesLength, defined onInternalCommandSchedulerand shared with the outbox's own column of the same name throughAmbientOrigin.MaxRolesLength); this type itself does not truncate, so an over-length role list is cut by the caller, keeping only the whole roles that fit, beforeFromCommandsees it.UserPermissionshas no width limit and is never truncated (:139-145). The cycleJsonExceptionfromFromCommandis not turned into a failure result by the scheduler, whosecatchcoversNotSupportedExceptiononly (InternalCommandScheduler.cs:92), so it surfaces to the scheduling handler as an exception.
AuditSaveChangesInterceptor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/AuditSaveChangesInterceptor.cs:38· Level 11 · class (sealed)
- What it is: the EF Core interceptor that stamps
CreatedOn/CreatedBy,LastModifiedOn/LastModifiedByandDeletedOn/DeletedByon everyIAuditableEntityentry immediately before the write (AuditSaveChangesInterceptor.cs:10-36). On PostgreSQL and SQLite it also writes theRowVersionoptimistic-concurrency token, because neither engine generates one server-side (:21-27). It is the first of the interceptors the framework installs and the reason no handler anywhere in ADC or Store sets an audit field by hand. - Depends on:
ApplicationDbContext(forCurrentSaveUserId, the engine capabilities and the change tracker),IAuditableEntity,IRowVersioned(only for theRowVersionproperty name),RowVersionStrategyread offDataSourceEngineCapabilities,OwnedDependents(to see edits confined to an owned value object), and the BCLTimeProvider, injected through the primary constructor (:38). - Concept introduced, the EF
SaveChangesInterceptoras the cross-cutting hook of the persistence layer.[Rubric §13, Observability & Operability]assesses whether audit, correlation and logging are wired once centrally rather than repeated per handler. An EFSaveChangesInterceptoris a hook EF calls at fixed points of the save pipeline:SavingChanges/SavingChangesAsyncbefore the write andSavedChanges/SavedChangesAsyncafter it. Choosing an interceptor over an override ofSaveChangesAsyncbuys three things: the logic runs on the synchronous and asynchronous paths alike, several interceptors compose in a defined order rather than fighting over one method body, and the concern lives in one class the module authors never see.[Rubric §8, Data Architecture]is engaged too, because "every row knows who wrote it and when" is a schema-level guarantee here, not a convention. - Concept introduced, stamping a transition rather than a value. The soft-delete stamps are not
driven by what
IsDeletedis but by whether it changed during this save (:14-20). That distinction is what makes the delete stamp behave like the creation stamp: it is written once, by the save that flipped the flag, and every later update of the same already-deleted row leaves it untouched. Reading the flag's value instead would rewriteDeletedOnon every subsequent write to a deleted row, which destroys the one fact the column exists to record. - Concept introduced, an owner is modified when its owned value object is. EF tracks an edit
inside an owned value object (an
OwnsOneaddress, anOwnsMoneyamount) on the owned entry and leaves the ownerUnchanged, so a state switch alone would skip the row even though it is rewritten. Without the owner-side walk the row would be saved with staleLastModifiedOn/Byand, on PostgreSQL and SQLite, an unchangedRowVersion(:28-35). - Walkthrough:
SavingChangesAsync(:40-50) andSavingChanges(:52-61): identical two-line bodies. Each pattern-matcheseventData.ContextagainstApplicationDbContext, callsStampAuditFields, then delegates tobase. The type test is the guard: a context that is not the framework's own is left completely alone.StampAuditFields(:63-106): reads the clock once per save viatimeProvider.GetUtcNow().UtcDateTime(:65) so every row in one save carries the same instant, and resolves the user once ascontext.CurrentSaveUserId ?? default(:66).CurrentSaveUserIdis the nullable user id the context was handed for this save (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:196, set at:197and:232), sodefaultis the sentinel for a system-originated write with no user behind it. It also decides once per save whether this engine needs a client-written row version:context.Engine.Capabilities.RowVersion == RowVersionStrategy.ClientStamped(:67), which is true for the PostgreSQL and SQLite engines (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/PostgreSQLDataSourceEngine.cs:44,SqliteDataSourceEngine.cs:43; the enum member is atRowVersionStrategy.cs:17).- The owner-side walk (
:71-75): before the switch, an entry that isUnchangedbut for whichOwnedDependents.HaveChanges(entry)is true is treated asModified; every other entry keeps its own state. Everything below then branches on that effective state, not onentry.State(:77). Clearing an optional owned reference tonullleaves no owned entry to see and is not stamped (:33-34). - The
Addedbranch (:79-89): sets all four creation and modification properties throughentry.Property(nameof(...)).CurrentValue, going through the change tracker rather than the CLR setters so the fields can stayinit-only or privately settable on the entity, then callsStampSoftDeleteTransitionwithwasDeleted: falseandStampRowVersion. A brand new row has no prior state, so an entity inserted already soft-deleted still gets its delete stamp (:85-88). - The
Modifiedbranch (:90-98): the interesting one. It setsLastModifiedBy/LastModifiedOn, and explicitly marksCreatedByandCreatedOnasIsModified = false(:91-92). That is the invariant: an update can never rewrite creation provenance, even if the caller mutated those properties on a tracked instance. It then runs the same soft-delete transition check, this time against the flag's stored value (:96), and stamps a fresh row version (:97). Detached,Unchanged,Deletedand the default (:99-103): deliberate no-ops. Note whatDeletedmeans here: a hard delete, which the framework does not use for auditable entities. A soft delete arrives asModified, because the entity only set a flag (see ADR-005 for soft delete versus erasure).StampRowVersion(:113-119): when the engine is client-stamped and the entity's model has aRowVersionproperty (entry.Metadata.FindProperty,:115), it writesGuid.NewGuid().ToByteArray()as the property's current value (:117). Setting the current value marks the property modified while EF keeps the loaded value as the original, so the UPDATE still carries the old token in its WHERE clause and a concurrent writer is detected (:108-111). On SQL Server therowversioncolumn is database-generated and this method writes nothing.WasDeleted(:122-123): the flag as the database has it, read from the property'sOriginalValue. Theis truetest rather than a cast is what keeps an unset or shadow value from throwing.StampSoftDeleteTransition(:130-144): compares the current flag against the prior one and returns immediately when they agree (:137-140), so no transition means no write at all. On a transition it writes both stamps in one direction: the resolved user and the save's instant on a delete, andnullon both columns on an undelete (:142-143).
- Why it's built this way: taking
TimeProviderinstead of callingDateTime.UtcNowmakes the stamps deterministic under test ([Rubric §14, Testability]), which is whatAuditSaveChangesInterceptorTestsrelies on (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Interceptors/AuditSaveChangesInterceptorTests.cs:13, with the soft-delete transitions pinned at:149(delete stamps written),:165(an update after a delete keeps the original stamp),:186(undelete clears both),:207(an active entity keeps them null) and:216(an insert that is already deleted is stamped), and the client-stamped row version on SQLite at:76). The class is registered as a singleton because it holds no per-save state at all (DependencyInjection.cs:66). - Where it's used: resolved from DI and attached in
ApplicationDbContext.OnConfiguring(ApplicationDbContext.cs:519, added at:307or:311). It is always first in the interceptor chain, which is what letsTenantSaveChangesInterceptor, the domain-event interceptor and the optionalAuditTrailSaveChangesInterceptorassume the audit stamps are already final when they run (ApplicationDbContext.cs:522-526,:314-318).
DomainEventSaveChangesInterceptor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:59· Level 8 · class (sealed, partial)
- What it is: the interceptor that turns domain events into durable messages. Before the write it
captures every pending event off the tracked aggregate roots and adds an
OutboxMessagerow for each, so events commit in the same transaction as the data. After the write it routes them: local events are dispatched in-process and their rows stamped processed, while integration events are left unprocessed for theOutboxProcessorto publish. On the async path the local rows are inserted under a short lease, so no replica's poller delivers an event a second time while this process is still handling it (DomainEventSaveChangesInterceptor.cs:14-42). It also owns the one post-commit hook for in-process delivery,DeferUntilCommit, which the event buses share. - Depends on:
IDomainEventDispatcher,IOutboxSignal,ILogger<T>, aTimeProviderand two optional options objects, all through the primary constructor (:59-65): theMessageBusSettingsthat suppliesIsOutboxEnabled, and theOutboxSettingsthat suppliesOutbox:LeaseSeconds;ApplicationDbContext,IAggregateRoot,IDomainEvent,IIntegrationEvent,OutboxMessage,OutboxFinalizer(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxFinalizer.cs:13), andInProcessDispatch(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/InProcessDispatch.cs:14), the per-event dispatch loop and lease release this type shares withInProcessEventBus(InProcessDispatch.cs:8-13). BCL:ConditionalWeakTable,ReferenceEqualityComparer,Func<CancellationToken, Task>. - Concept introduced, the dual-dispatch outbox (ADR-003) and its two failure modes.
[Rubric §6, CQRS and Event-Driven]assesses whether events are delivered reliably rather than optimistically, and[Rubric §29, Resilience and Business Continuity]assesses whether a crash at any point leaves the system recoverable. The mechanism has three moves. One, persistence: every captured event becomes an outbox row added to the sameDbContextbeforebase.SaveChangesAsyncruns, so the row and the aggregate change commit or fail together and no crash can lose an event that the data implies happened. Two, the in-process fast path: after the write, local events go straight to the dispatcher and their rows are stamped processed, so the background processor finds nothing to do. Three, the fallback: each local event is settled on its own, so when one event's dispatch throws only that event's row (and the rows of any later events sharing its ordering key) has its lease released and stays unprocessed, andoutboxSignal.Signal()wakes the processor to retry them. The routing split is what makes the pattern correct for extracted services: an integration event never takes the fast path, because in-process delivery would mark it processed and it would never reach the broker (:27-32). - Concept introduced, the local-row lease. Between the commit and the processed stamp, a local
event's row is unprocessed and visible to every replica's poller. In a multi-replica host that
window could deliver the event twice. So the async
SavingChangesAsyncbuilds aLocalLease(now plusOutbox:LeaseSeconds, under a fresh token;:104,:348-349) andApplyLocalLeasestamps it onto each local row (:301,:338-345). Three exits follow. Success: the processed stamp ends the row's life. Failed dispatch: the lease on the undelivered rows is released under its token so the processor retries after the normal processing delay, not after the full lease (:430-437). Crash: nothing releases it, and the rows are retried once the lease expires. Integration-event rows are never leased, because nothing in-process delivers them. The synchronousSavingChangespasses no lease (:117), because that path never dispatches in-process and its rows belong to the processor at once (:114-115). - Concept introduced, the outbox is a posture, not a constant. The interceptor reads
IsOutboxEnabledoff the injected message-bus options once, into the_outboxEnabledfield (:69), and that field is passed into every capture (:104,:117). The resolved posture is the explicitMessageBus:EnableOutboxvalue when a host sets one, and otherwise "on for any transport other than in-process" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/MessageBusSettings.cs:186), so a monolith running the in-process bus writes no outbox rows at all and dispatches everything directly, while a host on a broker keeps the durable path. A host that resolves no options at all keeps the outbox (:49-55,:69). This is why the type has two behavioral axes rather than one:context.Engine.Capabilities.IsRelational(is this a relational engine, and so one with an outbox table) and_outboxEnabled(does this host want it), and both must be true to take the durable branch (:277). The engine axis is read off the context'sDataSourceEngineCapabilities: SQL Server, PostgreSQL and SQLite declareIsRelational: true, Cosmos declaresfalse(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:44,PostgreSQLDataSourceEngine.cs:42,SqliteDataSourceEngine.cs:41,CosmosDataSourceEngine.cs:43). - Concept introduced, unbacked events are isolated per event. When the save took the
non-durable branch, no outbox row backs any local event, so nothing will ever retry one. The flush
detects that case by
LocalOutboxEntries.Count == 0and dispatches throughInProcessDispatch.DispatchUnbackedAsync(:412-416). That method hands the dispatcher one event at a time and catches each failure, logging it at Error through the source-generatedLogUnbackedDispatchFailed, which names the event type and states that the event is not retried (InProcessDispatch.cs:90-109,:147-148). One throwing handler therefore cannot take the later events of the save down with it. The isolation is per event, not per handler: the dispatcher still runs one event's handlers in sequence, so a throwing handler skips the handlers registered after it for that same event, and a host whose handlers must all run, or run again, enables the outbox (InProcessDispatch.cs:76-84, restated in the constructor remarks at:53-55). - Concept introduced, backed events are settled per event too. When rows do back the local
events, the flush calls
InProcessDispatch.DispatchBackedAsync(:417-423), which walksLocalEventsandLocalOutboxEntriesside by side (built together in capture order, one entry per event,:419) and returns two lists: the entries of the events that succeeded and of those that did not (InProcessDispatch.cs:36-74). Only the delivered rows are stamped processed; the others are handed back to the processor. Dispatching the whole set in one call would stop at the first throwing event with nothing marked processed, so the processor would re-run the handlers of every event before the failure (InProcessDispatch.cs:16-21). A failure also holds back the later events that share the failed event's ordering key (IHasOrderingKey): they go to the processor unattempted, behind their predecessor, so that key is never delivered out of order, while unkeyed events and other keys carry on (InProcessDispatch.cs:23-27,:52-56,:68-69). Each failure is logged at Warning throughLogLocalEventDispatchFailed(InProcessDispatch.cs:65,:144-145). A cancellation is not a delivery failure: the exception filter lets it propagate (InProcessDispatch.cs:63). - Walkthrough (this is the densest type in the group; read it as capture, then route, then
defer):
- Fields and three static weak tables (
:67,:69,:71,:78,:86,:94). The fields are the clock, an injectedTimeProviderwith no default (:63,:67), so a test can drive theProcessedOnstamp and the lease expiry directly, the resolved outbox posture, and the lease length in seconds (:71, taken fromOutboxSettings, or its default when the host resolves no options).StateTableholds theCapturedStatebetween saving and saved;DeferredTableholds, per context inside a transaction, a list ofFunc<CancellationToken, Task>post-commit work items run in the order they were deferred, each closing over whatever owns it (this interceptor's captured state, or a batchInProcessEventBuspublished), so the factory can flush through a static entry point with no DI edge back to either type (:80-86);CaptureExclusionTableholds the aggregate instances a save must skip.ConditionalWeakTableis chosen throughout so the interceptor can stay a singleton without ever keeping a context alive or needing cleanup code (:73-77). SavingChangesAsync/SavingChanges(:97-107,:110-120): both callCaptureEventsAndPersistToOutboxfor anApplicationDbContext, then delegate to base. The async one passesNewLocalLease(), the sync onelocalLease: null. Capture is synchronous by necessity: the outbox rows must be in the change tracker before EF generates the SQL.CaptureEventsAndPersistToOutbox(:248-322), the heart of the type:- It first calls
DiscardAbandonedCapture(:254, defined at:356-373). A previousSavingChangesthat never reachedSavedChanges(a failed save, then an execution-strategy retry) left its outbox rows tracked asAdded. Re-capturing on top would write a second row per event and publish everything twice, so everyAddedOutboxMessageon the context is detached first. The comment justifies the blanket detach: this interceptor is the only writer of outbox rows, and a completed save leaves noneAdded(:363-366). - It reads the exclusion set (
:260) and projects the tracked aggregate roots that have events and are not excluded intoAggregateCapturevalues (:262-266), taking a snapshot copy of each event list, and returns early when nothing carried an event (:268-269). - When
context.Engine.Capabilities.IsRelationalandoutboxEnabledare both true (:277), it readscontext.CurrentOutboxOriginonce into a local (:288) rather than per event, then walks the flattened event list filtered byNeedsOutboxRow(:291-308): every event that passes the filter getsOutboxMessage.FromDomainEvent(domainEvent, origin), then is sorted, then its row is added to the outbox set.NeedsOutboxRow(:332-335) keeps everyIIntegrationEvent, and keeps a local event only when the injected dispatcher is the framework'sDomainEventDispatcherand reports a handler for the event's exact type throughHasDomainEventHandlers; any other dispatcher keeps every local event. A local event nothing in this host handles therefore gets neither a row nor an in-process dispatch (:24-26,:324-331). The comment states why a single read is correct rather than a shortcut (:283-287): the interceptor is a singleton and the context only carries the root provider, so a scoped service is not reachable from inside this method at all; the live accessorCurrentOutboxOriginalready resolved the ambient scope once for this save, and every row of the save is one scope's work, so stamping every row with the same captured value is correct by construction, not an approximation. AnIIntegrationEventonly flipshasIntegrationEvents; anything else is leased throughApplyLocalLease(:301) and joins bothlocalsandlocalOutboxEntries. TheAddcall comes after that sorting step (:307), preceded by a plain comment recording that EF'sDbSet.Addis intentionally synchronous andAddAsyncis only for special value generators (:306); no analyzer suppression wraps it. - Otherwise, when the context has no outbox table (Cosmos being the example named in the
comment) or the host turned the outbox off, every event is treated as local (
:312-318): nothing could carry it to a processor anyway, and for the in-process transport that is the whole delivery path rather than a degradation. No rows exist in that branch, so no lease does either, andlocalOutboxEntriesstays empty, which is the signal the flush uses to pick the per-event dispatch. - Finally it stores the
CapturedState, including the lease token, under the context (:320-321).
- It first calls
SavedChangesAsync(:123-132) callsDispatchAndFinalizeAsync(:379-396, a non-async method returningTask, so it returnsTask.CompletedTaskon its early exits and hands backFlushStateAsync's task directly), which pulls the state, removes it from the table, and then forks. With an active transaction it clears the captured events now (so a second save in the same transaction cannot re-capture them) and defers a closure over the captured state,ct => FlushStateAsync(context, state, ct), throughDeferUntilCommit(:386-393). Without one it flushes immediately (:395).FlushStateAsync(:403-462): starts fromdelivered= every local row andundeliveredempty (:407-408), then dispatchesLocalEventsif any (:410-424), throughInProcessDispatch.DispatchUnbackedAsyncwhen no local row backs them and throughInProcessDispatch.DispatchBackedAsyncotherwise, which replaces the two lists with its per-event outcome (:420-422). It then removes the captured events (:426), stamps only thedeliveredrows processed throughOutboxFinalizer.MarkProcessedAsync(:428, a single set-basedExecuteUpdateplus a tracker sync rather than a nested save,OutboxFinalizer.cs:27-31,:39-42,:44-54), and, when anything is undelivered, releases the lease on just those rows throughInProcessDispatch.ReleaseLeaseAsyncand signals the outbox (:430-437); otherwise it signals only when integration events are present (:438-441). Thecatchis a deliberate catch-all, wrapped in a targetedCA1031suppression whose justification is that in-process dispatch must not fail the committed save (:443-445). The comment states it is reached only by a cancellation or a failed finalize, because a handler failure is settled per event insideDispatchBackedAsync(:447-450). Neither outcome was recorded, so it logs through the source-generatedLogDispatchError(:451,:476-477), releases the lease on every local row of the save (:452; a row already stamped processed is unaffected and its handlers do not run again), and signals the processor when the save wrote any row (:454-455); thefinallyremoves the events again, idempotently (:457-461). BecauseDispatchUnbackedAsyncswallows each event's failure, an unbacked handler failure never reaches thatcatcheither.InProcessDispatch.ReleaseLeaseAsync(InProcessDispatch.cs:123-142), the release both branches call: returns at once when there is no lease token or no rows (:129-130). Otherwise it callsOutboxFinalizer.ReleaseLeaseAsyncwithCancellationToken.Noneon purpose, because a dispatch that failed by cancellation still has to hand its rows back (:115-116,:134; the guarded update isOutboxFinalizer.cs:67-84). It is best effort: a failure is logged throughLogLeaseReleaseFailed(:140,:150-151) and swallowed under a targetedCA1031suppression (:136-138, "the lease expires on its own"), so the rows simply wait out the lease and the save that already committed is never failed by the release.SavedChanges, the synchronous path (:144-158): it cannot await the dispatcher, so it does not try. For a host with the outbox on and a context whose engine is relational (the property pattern{ Engine.Capabilities.IsRelational: true }at:147) it removes the state, clears the captured events (which is what stops a later async save from re-capturing and duplicating them) and signals the processor when the save wrote any row (:153-154), leaving delivery entirely to the outbox. A context without outbox support, and a host running with the outbox off, keep the legacy no-op, because with no rows written there is nothing for a processor to pick up and clearing the events here would lose them outright (:135-143).RemoveCapturedEvents(:470-474): removes exactly the captured events viaRemoveDomainEvents, never a wholesale clear, for the reasonAggregateCaptureexists.FlushDeferredAsync/DropDeferred(:166-175,:197): the two internal static entry pointsDbContextFactorycalls at commit and at rollback.FlushDeferredAsyncremoves the context's list and awaits each work item in the order it was deferred (:171-174). A missed flush is explicitly safe: the rows stay unprocessed and the outbox delivers them once their lease expires (:160-165).DropDeferreddiscards the list, because the rows rolled back with the transaction and an execution-strategy retry must not flush the aborted attempt's events (:191-196).DeferUntilCommit(context, work)(:188-189,internal static): appends a post-commit work item to the context'sDeferredTablelist. The doc comment names it the one post-commit hook for in-process delivery, shared by this interceptor andInProcessEventBus, so the two cannot disagree on when a transactional unit's events reach their handlers, and requires the work not to throw, because it runs after the commit where a failure can no longer roll anything back (:177-187). The ordering rule it implements is that in-process handlers must never act on state that could still roll back: email, cache writes and pushes issued from a handler are not transactional, so dispatching them before the commit would leave real side effects behind an aborted transaction, and an execution-strategy retry would repeat them once per attempt (:35-40). Because the factory only ever calls the staticFlushDeferredAsync, it has no constructor dependency on this interceptor or on the buses, which keeps the persistence graph acyclic.BeginCaptureExclusion/EndCaptureExclusion(:214-223,:230): the narrow hook forIDENTITY_INSERTbatching.DbContextFactorysplits a save into one round per identity table and temporarily marks the other tables' entriesUnchanged(DbContextFactory.cs:397-415); those rows are not written this round, so capturing their events now would persist and clear an event ahead of the insert that justifies it. The exclusion set is built withReferenceEqualityComparer.Instance(:222) and cleared in afinally(DbContextFactory.cs:445-448). The remarks explain why exclusion is by instance and not by entity state (:207-211): skipping everyUnchangedaggregate would also drop events raised on an already-saved aggregate, which is how the identity module publishes its registration events.
- Fields and three static weak tables (
- Why it's built this way:
ADR-003 specifies
at-least-once delivery, with the in-process path as an optimization and the outbox as the
guarantee. The lease narrows the duplicate window that optimization would otherwise open on a
multi-replica host, without giving up the guarantee: an unreleased lease only delays the
fallback, it never drops a row. Deferring past the commit is
ADR-014's Transactional
decorator honored at the persistence layer: business failures roll back, and a rolled-back save
must deliver nothing. The type is
partialfor its one source-generated[LoggerMessage]method,LogDispatchError(:476-477); the per-event and lease-release log lines live inInProcessDispatchand are written through this type's logger, so they keep its category (InProcessDispatch.cs:12). It is singleton-safe because every piece of per-save state lives in a weak table keyed by context. - Where it's used: registered as a singleton (
DependencyInjection.cs:67), attached last of the save-time trio inApplicationDbContext.OnConfiguring(ApplicationDbContext.cs:520,:529,:533) so it sees final audit stamps and final tenant values; driven at transaction boundaries byDbContextFactory. ItsDeferUntilCommithook is also called by the event buses for publishes made inside an open transaction (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:121,:154;MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerEventBus.cs:99). Pinned byDomainEventSaveChangesInterceptorTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Interceptors/DomainEventSaveChangesInterceptorTests.cs:19),DomainEventSaveChangesInterceptorOutboxRoutingTests(.../DomainEventSaveChangesInterceptorOutboxRoutingTests.cs:28),DomainEventSaveChangesInterceptorOutboxDisabledTests(.../DomainEventSaveChangesInterceptorOutboxDisabledTests.cs:22, whoseSaveChangesAsync_AThrowingHandler_DoesNotStopTheNextEvent_AndLogsThatNothingRetriesat:87pins the per-event isolation),DomainEventSaveChangesInterceptorLocalLeaseTests(.../DomainEventSaveChangesInterceptorLocalLeaseTests.cs:25),DomainEventSaveChangesInterceptorHandlerPresenceTests(.../DomainEventSaveChangesInterceptorHandlerPresenceTests.cs:22, whoseSaveChangesAsync_UnhandledLocalEvent_WritesNoRowAndClearsTheEventat:49pins theNeedsOutboxRowfilter) andDomainEventCaptureExclusionTests(.../DomainEventCaptureExclusionTests.cs:28). - Caveats / not-in-source:
DiscardAbandonedCapturedetaches everyAddedOutboxMessageon the context, which is correct only while this interceptor remains the sole writer of outbox rows. That is true in the current source, and the comment states the assumption (:363-366), but it is an invariant a future outbox writer would have to respect. Also, a crash between commit and the processed stamp is not repaired by this type at all: recovery is the lease expiring and a poller taking the rows, so the worst-case delay isOutbox:LeaseSeconds(default 300,OutboxSettings.cs:100). With the outbox off there is no recovery at all: a failed unbacked event is logged at Error and lost, by design. A deferred work item that throws insideFlushDeferredAsyncstops the remaining items of that list; the contract onDeferUntilCommitis that work must not throw (:183-184), whichFlushStateAsynchonors through its catch-all.
TenantSaveChangesInterceptor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Interceptors·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/TenantSaveChangesInterceptor.cs:44· Level 8 · class (sealed)
- What it is: the write side of multi-tenancy. It stamps
ITenantEntity.TenantIdon inserts and refuses any save that would touch another tenant's row (TenantSaveChangesInterceptor.cs:9-13), or that would write a tenanted row from a scope that resolved no tenant and was not declared an all-tenants system scope (:26-36). - Depends on:
ApplicationDbContext(forCurrentTenantId,IsAllTenantsScopeand the change tracker),ITenantEntity,CrossTenantWriteException, and EF Core'sEntityEntry<T>. It has no constructor at all: every member is static and the class is pure policy over the entries. - Concept introduced, read isolation and write isolation are separate mechanisms.
[Rubric §11, Security]assesses whether a boundary holds without caller cooperation. Tenancy in this framework is enforced twice, independently. On reads it is a named EF query filter,"Tenant", applied inApplicationDbContext.ApplyTenantFilters(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:757-817), which composes by AND with the"SoftDelete"filter (ApplicationDbContext.cs:729-737) and embeds the executing context as a constant so one cached model serves every tenant (ApplicationDbContext.cs:738-745,:435-436). On writes it is this interceptor. The independence is the point and is called out in the remarks (:37-42): a caller who bypasses the read filter with EF's own parameterlessIgnoreQueryFilters()can read across tenants, but still cannot write across them.[Rubric §30, Compliance and Data Governance]applies for the same reason: separation is a property of the engine here, not of reviewer vigilance. - Concept introduced, no tenant is not the system scope. A scope that resolved no tenant is
unrestricted only when it was declared an all-tenants system scope (
ITenantContext.SetAllTenants, read throughApplicationDbContext.IsAllTenantsScope,ApplicationDbContext.cs:166), which is the same flag the read filter requires (IsAllTenantsScope || TenantId == CurrentTenantId,ApplicationDbContext.cs:748). From that scope an entity that already carries a tenant is written as-is, which is how a seeder or a background worker drains one tenant's work. A scope that merely resolved nothing (a request on a host withRequireTenantoff, a context created outside a scope) reads no tenant-owned row, so it may not write one either: inserting a row that names a tenant, and updating or deleting a row that carries one, are refused. An untenanted insert is refused in both scopes, because nothing could supply the missing value (:26-36). - Walkthrough:
SavingChangesAsync/SavingChanges(:47-56,:59-67): the same two-line shape as the audit interceptor, both routing toApplyTenant.ApplyTenant(:72-106): readscontext.CurrentTenantIdonce per save (:76), because that property walks a live accessor into the scoped tenant context (ApplicationDbContext.cs:150) and a save must be judged against a single value. It then derivesallTenantsScopeascurrentTenantId is null && context.IsAllTenantsScope(:78-80): the flag is consulted only when no tenant resolved, so a resolved tenant always wins, exactly as on the read side. It enumeratesChangeTracker.Entries<ITenantEntity>()filtered by!entry.Metadata.IsOwned()(:86-87) and switches on state:AddedtoStampOrVerifyInsert,ModifiedandDeletedtoVerifyExistingRowwith the operation name, both receiving the tenant and the all-tenants flag (:89-104), everything else a no-op. Owned types are excluded on both sides of the boundary for the same reason (:82-85): an owned value is only reachable through its owner, so the owner's tenant already is the row's tenant and stamping the copy would only invite the two to disagree.StampOrVerifyInsert(:114-143): five outcomes, in order. No current tenant and no declared tenant throwsCrossTenantWriteException.ForUnresolvedTenant(:125-126), because silently writing a row no tenant can ever read is worse than failing the save. No current tenant but an explicitly declared one is allowed through only from an all-tenants scope (:128-130): that is a seeder or a per-tenant background job. The same insert from a scope that is not all-tenants throwsForUnscopedWrite(:132). A current tenant with no declared value gets the stamp (:135-139). A current tenant that disagrees with the declared value throwsForMismatch(:141-142).VerifyExistingRow(:151-183): returns immediately for an all-tenants scope (:157-158), which keeps the declared system context unrestricted exactly as it is on the read side. When the scope resolved no tenant and is not all-tenants, it asksFirstTenantedfor the first recorded tenant value and throwsForUnscopedWritewhen the row carries one; an untenanted row passes (:162-169). Otherwise it checks both recorded values throughFirstForeignTenant(:171-176): the property'sOriginalValuecatches touching another tenant's row, and itsCurrentValuecatches reassigning this row to another tenant within the same save, and a foreign value throwsForMismatch(:178-182).FirstForeignTenant(:191-197) andIsForeign(:212-213): the original is reported in preference to the current one, because "you touched another tenant's row" is a more useful diagnosis than "you renamed its owner" (:185-190).IsForeigntreats null and empty as absent, and compares withStringComparison.Ordinal.FirstTenanted(:203-209): the first of the original and current values that is present, original first, or null when the row carries no tenant on either side (:199-202).EntityTypeName(:216-217):ClrType.FullName ?? ClrType.Name, used only for the failure message.
- Why it's built this way: one concern per interceptor and registration order is execution
order (
:15-21). This one sits deliberately between the audit and domain-event interceptors: the audit stamps are already written when it runs, and the outbox rows the domain-event interceptor adds afterwards describe an entity whose tenant is final. It is also always registered and inert by default (:22-25,DependencyInjection.cs:69-72): it is a no-op for every entity that does not carryITenantEntity, which is every entity in a host that never adopted tenancy, so that host pays nothing while a host that does adopt tenancy can never accidentally leave the write guard off. Requiring an explicit all-tenants declaration rather than treating "no tenant" as "system" keeps a scope that forgot to resolve a tenant from silently writing tenant-owned rows.OnConfiguringresolves it withGetServicerather thanGetRequiredService(ApplicationDbContext.cs:527) so a directly-constructed test or design-time context still builds. See ADR-073. - Where it's used: registered as a singleton in
AddInfrastructure(DependencyInjection.cs:72) and attached second in the interceptor chain (ApplicationDbContext.cs:529); exercised byTenantSaveChangesInterceptorTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Tenancy/TenantSaveChangesInterceptorTests.cs:12, including the unscoped insert, update and delete cases at:60,:75and:92, the all-tenants update at:107, the owned-value carve-out at:212and the still-builds-without-it case at:227) and by the registration tests in.../Persistence/Tenancy/AddMultiTenancyTests.cs:19. - Caveats / not-in-source: whether any deployed host in this workspace actually opts into
multi-tenancy is Not determinable from source, since the guard is registered unconditionally and
is inert until an entity implements
ITenantEntity.
InternalCommandOriginCapture
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandOriginCapture.cs:21· Level 9 · class (internal sealed)
- What it is: the snapshot step of the internal-command queue: one method,
Capture(), that reads the ambient request context a scheduled command must carry onto its row (the scheduling principal, roles and permission claims, the tenant, the correlation id, the trace and span ids, the trace flags) and returns it as anInternalCommandOrigin(InternalCommandOriginCapture.cs:8-12,:21-42). TheInternalCommandProcessorrestores those values around the deferred execution. - Depends on:
ICurrentUserService,ITenantContextandICorrelationContextthrough the primary constructor (:21-24);InternalCommandOriginas the value it builds;AmbientOrigin.FlattenRolesfor the roles andAmbientOrigin.FlattenPermissionsfor the permission claims; BCLSystem.Diagnostics.Activityfor the trace and span ids and the trace flags. - Concept introduced, capture is scoped because what it reads is scoped.
[Rubric §13, Observability & Operability]assesses whether the identity and correlation of a request survive an asynchronous hop. The snapshot has to describe the request that is scheduling the command, and all three services it reads are request-scoped, so the capture is registered scoped too (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs:164, rationale in the remarks at:13-17). Pulling the capture out of the scheduler into its own type gives the snapshot one owner with one dependency set, soInternalCommandSchedulertakes a singleInternalCommandOriginCaptureargument instead of the three ambient services. - Walkthrough:
Capture()(:28-41): readsActivity.Currentonce (:30), then builds theInternalCommandOriginfromcurrentUserService.UserId, the roles flattened throughAmbientOrigin.FlattenRoles(currentUserService.Roles), the permission claims flattened throughAmbientOrigin.FlattenPermissions(currentUserService.User),tenantContext.TenantId,correlationContext.CorrelationId, the activity'sTraceId/SpanIdas strings, and itsActivityTraceFlagscast tobyte(the sampling decision), eachnullwhen no activity is running (:32-40).
- Why it's built this way: roles go through the shared
AmbientOriginhelper, which the outbox capture uses as well, so the outbox hop and the internal-command hop store roles in the same shape (:15-16). The class holds no state of its own; every value comes from the scoped services at the momentCapture()runs. - Where it's used: registered with
TryAddScoped(DependencyInjection.Jobs.cs:164); called once per scheduled command byInternalCommandScheduler(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandScheduler.cs:85); constructed directly byInternalCommandTestHarness(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/InternalCommandTestHarness.cs), and pinned byInternalCommandTraceFlagsTestsandInternalCommandOriginWithheldRoleTestsin the same folder and byMultiFactorBearerWithholdingTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authorization/MultiFactor/MultiFactorBearerWithholdingTests.cs).
InternalCommandScheduler
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/InternalCommandScheduler.cs:36· Level 10 · class (internal sealed, partial)
- What it is: the write side of the internal-command queue,
IInternalCommandScheduler's implementation: it turns a command into anInternalCommandMessagerow, enrolls it in the caller's transaction if one is open (owing the processor a wake until the commit succeeds), and otherwise saves and signals the processor at once (InternalCommandScheduler.cs:36-147). - Depends on:
IDbContextFactory,IDataSourceResolver,IOptions<InternalCommandsSettings>,InternalCommandOriginCapture,IInternalCommandSignal,ILogger<InternalCommandScheduler>andTimeProvider, all through the primary constructor (:36-43), plusEnrolledCommandWakefor the deferred wake;InternalCommandMessageas the row it builds, andInternalCommandOriginas the captured scheduling context it hands toFromCommand;Result<Guid>andErrorfor its return shape. - Concept introduced, scheduling rides the caller's own save.
[Rubric §6, CQRS and Event-Driven]assesses whether deferred work is delivered reliably rather than optimistically, the same lens as the outbox.ScheduleAsyncnever opens aSaveChangesof its own when a transaction is already active: it resolves the caller's context throughdbContextFactory.GetDbContext(...)andAdds the row onto it (:101-105), so the queued command commits or rolls back exactly with the aggregate change that scheduled it. Inside a transaction it neither saves nor signals at once (:107-117): the caller's next save writes the row, or the transactional pipeline saves it just before the commit when no save follows (:109-111), and signalling then would only buy a query against a row that has not committed yet. Instead the wake is owed:EnrolledCommandWake.Defer(context, signal)(:114) records it, the unit of work releases it once after a successful commit and drops it on rollback (seeEnrolledCommandWake). Outside a transaction it saves immediately and always signals the processor (:123-128). - Walkthrough:
MaxRolesLength(:50):internal const int, aliased toAmbientOrigin.MaxRolesLengthso the internal-command queue and the outbox agree on the column width forUserRoles(a longer list keeps only the whole roles that fit) without restating the number.ScheduleAsync(command, delay, cancellationToken)(:59-66): the delay-based overload, sugar over theDateTimeOffset?overload: a positive delay becomes_timeProvider.GetUtcNow() + delay, anything else passesnullthrough.ScheduleAsync(command, runAt, cancellationToken)(:69-132), the primary path:- Returns
NullCommandError(aValidationerror,:52-53) for a null command (:74-77). - Normalizes a past
runAtto "now" rather than rejecting it (:83): a caller computing a deadline that already slipped wants the work done immediately, not an error to handle. - Captures the origin once with
originCapture.Capture()(:85), then builds the row viaInternalCommandMessage.FromCommand(command, scheduledOn, now, origin)(:88-99, the call at:90) inside atry/catch (NotSupportedException):System.Text.Jsonreports an unserializable payload this way, and the catch turns it into a logged failure result rather than letting it take down the handler that scheduled the command. The origin snapshot itself isInternalCommandOriginCapture's job. - Resolves the context for
_settings.DataSource/DatabaseNamethroughdataSourceResolver.ResolveLogical(:101-102) and adds the row with a synchronousAdd, commented as the EF guidance thatAddAsyncis only for special value generators (:104-105). - If
context.Database.CurrentTransaction is not null, defers the wake throughEnrolledCommandWake.Defer, logsLogEnrolledand returns without saving or signalling (:107-117); the signal fires after the commit succeeds, and the polling interval is only the backstop. - Otherwise calls
context.SaveChangesAsync(origin.UserId, cancellationToken)as the scheduling user (:123): the row itself is neither auditable nor an aggregate root, but the context is shared with the calling handler's repositories, so anything else pending on it is flushed by this save and must be stamped with the real user rather than the system (:119-122). It then signals the processor whether or not the row is due yet (:125-128): a due row runs on the wake, and a not-yet-due row costs one fetch but re-arms the processor's smart wait on itsScheduledOn, which the processor would otherwise only learn at the next polling interval and so run the command late.
- Returns
SerializationError(commandType)(:134-137): theError.Unexpectedfactory (InternalCommands.NotSerializable) for the not-serializable branch, so an unqueueable command is classed as an unexpected programming error rather than a business failure.LogEnrolled,LogScheduled,LogSerializationFailed(:139-146): source-generated[LoggerMessage]partials at Debug, Debug, and Error respectively.
- Why it's built this way:
internal sealed partialbecause it is the one implementation ofIInternalCommandSchedulerin the framework and callers depend on the interface, not the class; the no-op-on-open-transaction branch is the same ordering disciplineDomainEventSaveChangesInterceptor.DeferUntilCommitenforces for domain events, applied here to a queued command instead of an in-process dispatch. See ADR-114. - Where it's used: registered in DI (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Jobs.cs, 1 reference); the entry point every caller ofIInternalCommandScheduler.ScheduleAsyncgoes through. Pinned byInternalCommandSchedulerTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/InternalCommands/InternalCommandSchedulerTests.cs), exercised throughInternalCommandTestHarness, and referenced byDbContextFactoryTransactionTests,WebhookSubscriptionSqlServerTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.SQLServer.Tests/Webhooks/WebhookSubscriptionSqlServerTests.cs) and, from a consumer,AuthenticationServiceTests(MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/AuthenticationServiceTests.cs). - Caveats / not-in-source: a null command returns
Result.Failurewith aValidationerror (:52-53,:74-77) rather than throwingArgumentNullException; the source does not explain the choice in a comment.
InternalCommandsDisabledNoticeService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandsDisabledNoticeService.cs:20· Level 0 · class
- What it is: an
IHostedServicethat logs a single informational notice on startup for a host that writesInternalCommandsrows but runs neitherInternalCommandProcessornorInternalCommandCleanupService(InternalCommandsSettings.Enabled == false). - Depends on:
ILogger<InternalCommandsDisabledNoticeService>, the[LoggerMessage]source-generator pattern. - Concept: a "notice service" idiom that pairs a settings toggle with a one-time explanatory log line rather than staying silent about a deliberate configuration choice.
[Rubric §13: Observability & Operability](assesses whether an operator can tell WHY the system behaves a certain way): a replica that never drains its own queue is easy to mistake for a bug without this notice. - Walkthrough:
StartAsync(InternalCommandsDisabledNoticeService.cs:24-28) calls the generatedLogQueueDisabled(InternalCommandsDisabledNoticeService.cs:33-36) once and returns;StopAsync(InternalCommandsDisabledNoticeService.cs:31) is a no-op. - Why it's built this way: the log message itself (
InternalCommandsDisabledNoticeService.cs:35) states the operational fact directly: scheduled work is executed only by a host that hasInternalCommands:Enabled=trueagainst the same databases, and no migration is needed to turn the queue on later because theInternalCommandstable is already part of the model. - Where it's used: registered in
DependencyInjection.cs(1 site), presumably conditioned onInternalCommandsSettings.Enabledbeingfalse.
InternalCommandsSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandsSettings.cs:15· Level 2 · class
- What it is: the bound options class for the
"InternalCommands"configuration section: it controls enablement, batching, retry backoff, claim leasing, retention, and which data source new work is scheduled against. - Depends on:
DataSourceandDataSourceKey,System.ComponentModel.DataAnnotations[Range]validation. - Concept: the options pattern used throughout the framework, here aligned with the outbox's own settings except in one place the doc comments call out explicitly: the retry backoff ceiling (
InternalCommandsSettings.cs:82-89).[Rubric §13: Observability & Operability]assesses whether operational knobs are documented well enough to tune safely; every property here carries a rationale comment, not just a default. - Walkthrough:
SectionName(InternalCommandsSettings.cs:18,"InternalCommands");Enabled(InternalCommandsSettings.cs:27, defaulttrue, the outbox's own posture: a host that schedules work must drain it, and a write-only replica sets itfalse);BatchSize(InternalCommandsSettings.cs:30-31,[Range(1,1000)], default50);MaxAttempts(InternalCommandsSettings.cs:40-41,[Range(1,20)], default5, aResult.Failurecounts as an attempt exactly like a thrown exception; the setting decides only WHEN a failing row is abandoned, because the abandonment is recorded on the row asDeadLetteredOn, so lowering the value never strands a row that is still pending, it only makes that row's next failure its last, per the doc comment atInternalCommandsSettings.cs:33-39);PollingIntervalSeconds(InternalCommandsSettings.cs:51-52,[Range(1,3600)], default2, the fallback bound behind the smart wait: a row scheduled inside a transaction is woken by a signal released after the commit succeeds, so the interval is only the backstop for a wake that never arrives, such as a row another process wrote or a commit path that released no signal, per the doc comment atInternalCommandsSettings.cs:43-50);ProcessingDelaySeconds(InternalCommandsSettings.cs:59-60,[Range(0,600)], default0, as the outbox'sProcessingDelaySecondsdoes; raise it only to hold work back deliberately, per the doc comment atInternalCommandsSettings.cs:54-58);LeaseSeconds(InternalCommandsSettings.cs:70-71,[Range(10,3600)], default300, how long one replica's claim on a row lasts before another replica may reclaim it; the lease is renewed before each row of a claimed batch runs, so it bounds one handler, not the whole batch, per the doc comment atInternalCommandsSettings.cs:67-68);RetryBackoffBaseSeconds(InternalCommandsSettings.cs:79-80,[Range(1,3600)], default10, attemptnwaitsbase * 2^(n-1)with[0.8, 1.2]jitter, then capped);MaxRetryBackoffSeconds(InternalCommandsSettings.cs:88-89,[Range(1,86400)], default600, independent ofLeaseSecondsunlike the outbox, because a job queue wants a long lease for slow handlers but a short backoff ceiling);RetentionDays(InternalCommandsSettings.cs:95-96,[Range(0,3650)], default7,0keeps completed rows forever);DeadLetterRetentionDays(InternalCommandsSettings.cs:103-104,[Range(0,3650)], default0falls back toRetentionDays);CleanupIntervalHours(InternalCommandsSettings.cs:110-111,[Range(1,168)], default6);DataSource(InternalCommandsSettings.cs:119, defaultDataSource.SQLServer, must be relational: Cosmos has noInternalCommandstable, though the processor drains every relational source in use, not only this one);DatabaseName(InternalCommandsSettings.cs:127, defaultDataSourceKey.DefaultName, pointed at the source holding the aggregates that schedule work so the row and the aggregate change share one transaction). - Why it's built this way: the one divergence from the outbox's settings, a backoff ceiling decoupled from
LeaseSeconds, follows from a job queue wanting a long lease for slow handlers and a short ceiling on how long a transient failure parks a command (InternalCommandsSettings.cs:82-87); it is documented inline rather than left implicit. - Where it's used: read via
IOptions<InternalCommandsSettings>acrossDependencyInjection.Jobs.cs(5 sites),InternalCommandCleanupService(4),InternalCommandScheduler(4),InternalCommandLaneProcessor(3), the test harness (3),InternalCommandAdministration(2),InternalCommandProcessor(2),WebhookDeliveryLane(2),DataSourceBranchingFitnessTests(1), and the cleanup-service and lane test harnesses. - ADRs: ADR-114, ADR-142.
InternalCommandAdministration
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandAdministration.cs:34· Level 13 · class
- What it is: the operator-facing administration surface for the internal-commands queue: count pending work, list and paginate dead letters, requeue them, and purge completed rows, fanned out across every relational data source (and tenant) this host owns.
- Depends on:
IServiceScopeFactory,IOptions<InternalCommandsSettings>(InternalCommandsSettings),FrameworkTableTargets,IInternalCommandSignal,TimeProvider,IDbContextFactory,ApplicationDbContext,InternalCommandMessage,TenantDataSourceTarget,Error/Result(Domain layer). - Concept: the same operator-lever shape as
IOutboxAdministration: count / list-dead-letters / requeue / purge, fanned out per owned data source.[Rubric §8: Data Architecture](assesses how a system handles database-per-service and multi-tenant fan-out): every operation here resolves its own target set rather than assuming a single database.[Rubric §13: Observability & Operability]: requeue and purge are explicit, logged operator actions, not silent background behavior. - Walkthrough: the primary constructor (
InternalCommandAdministration.cs:34-40) takes six required parameters, with target selection delegated to an injectedFrameworkTableTargetsrather than a registry, a resolver and optional tenancy options;MaxPageSize(InternalCommandAdministration.cs:43,500) bounds one page so an admin call cannot pull the whole table;MaxSkip(InternalCommandAdministration.cs:50,10_000) bounds the paging offset, because paging is merged across every source and each source returns up toskip + takerows into memory, so an unbounded skip would let one call materialize a whole dead-letter table (kept forever when retention is off) per source;SkipError/TakeError/OlderThanError(InternalCommandAdministration.cs:52-59) are pre-builtError.Validationinstances,SkipErrorreading "Skip must be between 0 and 10000"; every operation returnsError.NotFoundErrorfromUnknownSourceError(InternalCommandAdministration.cs:245-248) when the requested source name matches no owned target;CountPendingAsync(InternalCommandAdministration.cs:65-85) sums aLongCountAsyncper target over rows whoseProcessedOnandDeadLetteredOnare both null (InternalCommandAdministration.cs:78): a row leaves the pending set only by being processed or by being stamped dead-lettered, never by its attempt count alone, so the count does not readMaxAttempts;ListDeadLettersAsync(InternalCommandAdministration.cs:88-147) rejects askipoutside0..MaxSkipor atakeoutside1..MaxPageSizeup front (InternalCommandAdministration.cs:94-98), then paginates across the MERGED result of every target: each target returns at mostperTarget = skip + takerows, a plainintsum that cannot wrap because both operands are capped (InternalCommandAdministration.cs:105, applied at:124; ordered byScheduledOnthenId), because "skip 50" must mean the same thing whether this host owns one database or four, then the merged list is re-ordered and re-paged in memory (InternalCommandAdministration.cs:141-144);RequeueAsync(InternalCommandAdministration.cs:150-205) resetsAttemptsto0and clearsDeadLetteredOn/ClaimedUntil/ClaimedByviaExecuteUpdateAsync(InternalCommandAdministration.cs:180-186) while deliberately preservingLastError("the only evidence of WHY this row needed requeuing"), then callssignal.Signal()(InternalCommandAdministration.cs:201) to wake the processor immediately instead of waiting for the next poll;PurgeProcessedAsync(InternalCommandAdministration.cs:208-243)ExecuteDeleteAsyncs processed rows at or before a caller-supplied cutoff;SelectTargets(InternalCommandAdministration.cs:255-256) is a one-line call totableTargets.Named(DataSource, DatabaseName, dataSource), recomputed per call because module assemblies can register entities after startup, and optionally narrowed to one name;VisitAsync<T>(InternalCommandAdministration.cs:263-274) opens a fresh DI scope via the sharedscopeFactory.CreateTenantScope(target)extension (InternalCommandAdministration.cs:270), which sets the tenant BEFORE theIDbContextFactorycontext is resolved, because the tenant is both what routes the scoped factory to the right database and what the query filter reads. - Why it's built this way: the tenant-before-context ordering and the deliberate
LastErrorpreservation are both stated inline as design decisions, not incidental;LogRequeued/LogPurged(InternalCommandAdministration.cs:276-280) give operators a durable audit trail of manual interventions on the queue. - Where it's used: registered in
DependencyInjection.Jobs.cs(1 site); referenced fromApplicationDbContext.cs(1); exercised byInternalCommandAdministrationTests.cs(4); the sharedSoftDeleteEnforcementTestsBaseinMMCA.Common.Testing.Architecture(1) checks its hardExecuteDeleteAsync/ExecuteUpdateAsynccalls against the restrict-delete-by-default convention. - ADRs: ADR-119.
InternalCommandCleanupService
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Administration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandCleanupService.cs:45· Level 13 · class
- What it is: a
PeriodicBackgroundServicethat periodically purges completed and dead-letteredInternalCommandsrows past their retention windows, across every relational data source (and tenant) this host owns. - Depends on:
PeriodicBackgroundService,IServiceScopeFactory,IOptions<InternalCommandsSettings>(InternalCommandsSettings),FrameworkTableTargets,TimeProvider,IDbContextFactory,ApplicationDbContext,InternalCommandMessage,TenantDataSourceTarget,BatchedDelete, an optionalIDistributedLock. - Concept: the same "sweep every owned target, isolate one source's failure from the rest" shape as
InternalCommandAdministration's own purge path; cross-reference rather than re-teach the tenant-before-context ordering.[Rubric §29: Resilience & Business Continuity]: an unreachable database on one source does not stop the sweep of the others. The hour-scale loop mechanics themselves (interval wait, cancellation, error logging) now come from the sharedPeriodicBackgroundServicebase rather than being hand-rolled here, so this section covers only what this type overrides. - Walkthrough: the type extends
PeriodicBackgroundService(timeProvider, logger)(InternalCommandCleanupService.cs:45-52) and takes five required constructor parameters plus an optionalIDistributedLock? cycleLock = null(InternalCommandCleanupService.cs:51), with target selection delegated to an injectedFrameworkTableTargets; it overridesCycleLock(InternalCommandCleanupService.cs:65, returnscycleLock: the purge is idempotent, so with a lock registered it runs on one replica per interval rather than once per replica, and the doc comment atInternalCommandCleanupService.cs:61-64notes thatAddInfrastructurealways registers one;nullsweeps on every replica),Interval(InternalCommandCleanupService.cs:68,TimeSpan.FromHours(CleanupIntervalHours)),StartupDelay(InternalCommandCleanupService.cs:74, equal toInterval, so the first sweep waits one full interval before competing with startup or migration work),IsEnabled(InternalCommandCleanupService.cs:77-89,falseand logsLogCleanupDisabledwhenRetentionDays <= 0),ExecuteCycleAsync(InternalCommandCleanupService.cs:92, forwards straight toPurgeAsync), andLogCycleFailure(InternalCommandCleanupService.cs:95, forwards toLogCleanupError);PurgeAsync(InternalCommandCleanupService.cs:102-151,internalso a test can drive one sweep without advancing the hour-scale timer) computescutoff = now - RetentionDaysand a separatedeadLetterCutoffusingDeadLetterRetentionDayswhen set, elseRetentionDays(InternalCommandCleanupService.cs:104-110); for each target fromGetTargets(InternalCommandCleanupService.cs:181-182, a one-line call totableTargets.Relational(DataSource, DatabaseName), the same set the processor drains) it opens a scope viascopeFactory.CreateTenantScope(target)(InternalCommandCleanupService.cs:118, sets the tenant before the context is resolved), resolves theApplicationDbContextthroughIDbContextFactory.GetDbContext(target.Source), deletes processed rows pastcutoffthroughBatchedDelete.DeleteAsync<InternalCommandMessage, DateTime?>, keyed onProcessedOn, with a callback that logsLogPurgedfor a non-zero count (InternalCommandCleanupService.cs:123-134), then callsSweepDeadLettersAsync(InternalCommandCleanupService.cs:157-175), which runs the sameBatchedDeleteshape keyed onDeadLetteredOn < deadLetterCutoffand logsLogDeadLetterPurgedthrough its callback, so a count is reported even when a later batch fails (InternalCommandCleanupService.cs:163); a per-source exception is caught (aCA1031suppression scoped to that onecatch) and logged viaLogSourcePurgeErrorrather than aborting the whole sweep (InternalCommandCleanupService.cs:143-149). - Why it's built this way: keying the dead-letter sweep on
DeadLetteredOnrather than a completion stamp reflects that a dead-lettered row never got one; the independentDeadLetterRetentionDayswindow lets operators keep abandoned commands around longer for diagnosis than ordinary completed ones; moving ontoPeriodicBackgroundServiceretires a hand-rolled interval loop that was nearly identical to the outbox and internal-commands processors' own loops. - Where it's used: registered as a hosted service alongside
InternalCommandProcessorinDependencyInjection.Jobs.cs(1 site); its retention posture is whatInternalCommandsDisabledNoticeService's log message calls out as the second job aEnabled=falsehost does not run; exercised directly byInternalCommandCleanupServiceTests.cs(4). - ADRs: ADR-114.
IInternalCommandSignal
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/IInternalCommandSignal.cs:9· Level 0 · interface
- What it is: a wake-up abstraction that lets code schedule an internal command and immediately nudge the processor, instead of the processor relying only on a fixed polling interval.
- Depends on: nothing first-party; the contract is
Task WaitAsync(TimeSpan, CancellationToken)plus a synchronousSignal()(IInternalCommandSignal.cs:12,21). - Concept introduced, the signal-based smart-wait pattern for the internal-commands job queue.
[Rubric §12: Performance & Scalability](assesses whether the system avoids wasted work and unnecessary latency): a plain fixed-interval poll trades latency for idle cost either way, while a signal lets a processor sleep long and still react immediately when work shows up. The doc comment onWaitAsync(IInternalCommandSignal.cs:14-17) states its intended caller directly:InternalCommandProcessor, "in place of a plain polling delay." - Walkthrough:
Signal()(IInternalCommandSignal.cs:11-12) marks that due work is available;WaitAsync(timeout, cancellationToken)(IInternalCommandSignal.cs:21) waits for a signal or untiltimeoutelapses, whichever comes first. - Why it's built this way: an interface, not a concrete
SemaphoreSlimdependency, so the processor, scheduler, and administration surface can share one wake mechanism through DI and a test harness can substitute a controllable fake. - Where it's used: implemented by
InternalCommandSignal; consumed byInternalCommandProcessor(the wait loop),InternalCommandScheduler, andInternalCommandAdministration(it signals after a successful requeue,InternalCommandAdministration.cs:201); registered inDependencyInjection.cs.
InternalCommandCycleResult
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandCycleResult.cs:17· Level 0 · record struct
- What it is: an internal, allocation-cheap result carrier for one polling cycle:
HasMoreDueWork(bool) andEarliestUpcoming(DateTime?) (InternalCommandCycleResult.cs:17). - Depends on: nothing first-party.
- Concept: a plain readonly record struct used purely to avoid tuple sprawl across the processor's internal methods; no new pattern to teach beyond the record-struct convention used elsewhere in the framework.
- Walkthrough: one line, two positional members:
HasMoreDueWorkdrives whetherInternalCommandProcessorre-polls immediately;EarliestUpcomingfeedsComputeWaitTime. - Why it's built this way:
internal readonly record structkeeps the per-cycle result on the stack rather than the heap, since it is produced and consumed once per poll cycle in a loop that can run continuously for the life of the host. - Where it's used: returned by
InternalCommandProcessor.ProcessDueCommandsAsync(InternalCommandProcessor.cs:119,134) and its private per-target helper, then read byExecuteAsync's wait loop.
InternalCommandLanes
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLanes.cs:10· Level 0 · class
- What it is: a one-property marker that tells the shared queue loop which stored command name a dedicated lane owns, so the shared loop leaves those rows alone.
- Depends on: nothing first-party.
- Concept: the exclusion half of the dedicated-lane pattern taught on
InternalCommandLaneProcessor; its mere presence in DI is the switch. - Walkthrough: the primary constructor takes
dedicatedCommandType(InternalCommandLanes.cs:10) and exposes it read-only asDedicatedCommandType(InternalCommandLanes.cs:13). - Why it's built this way:
InternalCommandProcessorasks for it withGetService, notGetRequiredService(InternalCommandProcessor.cs:301), so a host with no lane registers nothing and its fetch and count stay exactly the pending predicate; the lookup runs once from a scope on the first cycle, so the registration order of the lane and the processor does not matter (InternalCommandProcessor.cs:296-306). - Where it's used:
WebhookDeliveryLane.cs(2 sites, the one lane in Common),InternalCommandProcessorandInternalCommandLaneProcessor(1 site each); exercised byWebhookDeliveryLaneTests.csandInternalCommandProcessorTests.cs. - ADRs: ADR-114, ADR-142.
LaneBatchOutcome
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLaneProcessor.cs:684· Level 0 · record struct (private, nested)
- What it is: the private result of running one claimed lane batch:
Progressed,ChargedCountandReleasedCount(InternalCommandLaneProcessor.cs:684). - Depends on: nothing first-party.
- Concept: the lane's counterpart of
InternalCommandCycleResult, a stack-only carrier with no pattern of its own. - Walkthrough: built once at the end of
RunBatchAsync(InternalCommandLaneProcessor.cs:337) from the batch state and the release count. - Why it's built this way: the per-source step needs all three numbers to decide whether to re-poll at once: a full batch that progressed or charged rows, or any released row, sets
HasMoreDueWork(InternalCommandLaneProcessor.cs:288-289). - Where it's used: only inside
InternalCommandLaneProcessor.
ReceiverCooldowns
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/ReceiverCooldowns.cs:10· Level 0 · class
- What it is: a small in-memory table of receiver keys and the UTC instant each one's cooldown ends, private to one lane on one replica.
- Depends on: nothing first-party; a
Dictionary<string, DateTime>with ordinal comparison (ReceiverCooldowns.cs:12). - Concept: the per-receiver circuit breaker of the dedicated lane, taught on
InternalCommandLaneProcessor. It is not thread-safe and does not need to be: every read and write happens on the lane's one scheduling flow. - Walkthrough: the primary constructor takes the cooldown length (
ReceiverCooldowns.cs:10);IsCoolingDown(ReceiverCooldowns.cs:21-22) is true whileutcNowis before the stored end;Open(ReceiverCooldowns.cs:28-33) sets the end toutcNow + cooldownand returns true only on the transition from not cooling to cooling (so the caller counts and logs each opening once);Close(ReceiverCooldowns.cs:37) removes the key;Prune(ReceiverCooldowns.cs:41-47) drops every key whose cooldown ended more than one cooldown ago;Count(ReceiverCooldowns.cs:15) is a test hook. - Why it's built this way: the lane prunes at the start of every cycle (
InternalCommandLaneProcessor.cs:134), which keeps the table bounded by the receivers that failed recently rather than every receiver ever seen. - Where it's used:
InternalCommandLaneProcessor(1 site, the_cooldownsfield atInternalCommandLaneProcessor.cs:80);InternalCommandLaneProcessorTests.cs(3 sites). - ADRs: ADR-114, ADR-142.
InternalCommandMetrics
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandMetrics.cs:17· Level 1 · class (static)
- What it is: the static home of the OpenTelemetry
Meterand every instrument the internal-commands job queue publishes: processed/failed/dead-letter counters, execution duration and scheduling-lag histograms, pending-depth / oldest-due-age gauges, and the lane-tagged counters and gauges a dedicated lane adds. - Depends on:
System.Diagnostics.Metrics(Meter,Counter<T>,Histogram<T>,ObservableGauge<T>),ConcurrentDictionary<TKey,TValue>. - Concept introduced, per-instance observable gauges for a replicated background worker.
[Rubric §13: Observability & Operability]: the doc remarks onPendingDepthGauge(InternalCommandMetrics.cs:85-92) spell out that each replica reports only what IT last observed, never a cluster total, because the poll predicate already excludes rows another replica currently holds under lease; a source whose database is unreachable contributes zero for that cycle instead of a stale value. - Walkthrough:
MeterNameconstant (InternalCommandMetrics.cs:20,"MMCA.Common.InternalCommands") backs a singleMeter(line 22);ProcessedCounter/FailedCounter/DeadLetterCounter(InternalCommandMetrics.cs:38-61) are tagged bycommand_type(andreasonfor the latter two);DurationHistogramandLagHistogram(InternalCommandMetrics.cs:67-79) measure execution time and scheduling lag in seconds;PendingDepthGauge(InternalCommandMetrics.cs:93-97) is backed by_pendingDepth(line 28), read viaInterlocked.Read;OldestDueAgeGauge(InternalCommandMetrics.cs:105-109) is backed by aConcurrentDictionary<string,double>keyed bydata_source(lines 34-35) and observed throughObserveOldestDueAge(InternalCommandMetrics.cs:207-215);SetPendingDepth(line 168) andSetOldestDueAge(lines 173-174) are their only writers, both called fromInternalCommandProcessor. The lane instruments all carry alanetag:LaneShortCircuitedCounter(InternalCommandMetrics.cs:129-132, rows charged a failed attempt without being sent because their receiver was cooling down, counted once the charge is recorded),LaneReleasedCounter(InternalCommandMetrics.cs:138-141, claimed rows released uncharged after the batch start budget elapsed),LaneReceiverCooldownsCounter(InternalCommandMetrics.cs:144-147), and theLanePendingDepthGauge/LaneOldestDueAgeGaugepair (InternalCommandMetrics.cs:153-164), backed byConcurrentDictionarystores keyed by lane and by(lane, data_source)(InternalCommandMetrics.cs:115,121), written throughSetLanePendingDepth(line 179) andSetLaneOldestDueAge(lines 185-186) and observed byObserveLanePendingDepth/ObserveLaneOldestDueAge(InternalCommandMetrics.cs:188-205); both stores stay empty when no lane runs. - Why it's built this way: the counter/histogram/gauge split mirrors the questions an operator actually asks: throughput and failure rate (counters), how long work takes and how late it starts (histograms), and how deep and how stale the backlog currently is (gauges); the doc comment on
OldestDueAgeGauge(InternalCommandMetrics.cs:99-104) explains it is the signal a "wedged queue" alert fires on, distinct from the lag histogram which only reports rows that DID run. - Where it's used:
InternalCommandProcessor.cs(8 sites, one poll cycle at a time);InternalCommandLaneProcessor(6 sites, the lane instruments andMeterNamefor its activity source);MMCA.Common.Aspire'sOutboxPollFilterProcessor.cs(1 site) readsMeterNameto filter the paired suppressed telemetry; tests read it throughInternalCommandMeterRecorder.csandInternalCommandLaneProcessorTests.cs. - ADRs: ADR-041, ADR-114.
InternalCommandNameResolver
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandNameResolver.cs:19· Level 1 · class (static)
- What it is: a static, cached resolver between an
IInternalCommandCLR type and the string a queued row stores for it, honoring an optional declared-name attribute override in both directions. - Depends on:
System.Reflection(Type.GetCustomAttribute,AppDomain.GetAssemblies),ConcurrentDictionary<TKey,TValue>, the first-partyInternalCommandNameAttribute(not in this group). - Concept: reflection-with-caching for a hot path.
[Rubric §12: Performance & Scalability]: the doc comment onDeclaredNameCache(InternalCommandNameResolver.cs:21-26) is explicit that caching thenull(no-attribute) case too keeps the common unannotated command to one reflection lookup per type per process, rather than one per scheduled row. - Walkthrough:
GetDeclaredName(InternalCommandNameResolver.cs:35-38) readsInternalCommandNameAttributewithinherit: false(a derived command cannot silently borrow its base's identity) viaGetOrAdd;GetStorageName(InternalCommandNameResolver.cs:47-51) returns the declared name if present, else falls back throughAssemblyQualifiedName→FullName→Name, the same fallback chain the outbox uses;FindTypeByDeclaredName(InternalCommandNameResolver.cs:67-73) is the reverse lookup for a stored name that is not a CLR type name: it lazily scans loaded, non-dynamic assemblies and checksIsDefinedbeforeGetDeclaredName, deliberately in that order, so only the handful of annotated types pay for constructing the attribute;GetLoadableTypes(InternalCommandNameResolver.cs:82-92) degrades to the types that DID load on aReflectionTypeLoadException, so one bad type in an assembly cannot abort the scan. - Why it's built this way: the lazy
Where/SelectMany/FirstOrDefaultchain stops at the first match instead of materializing every loaded type (InternalCommandNameResolver.cs:60-64), which matters because this reverse path is reached once per stored name that resolves (the caller,InternalCommandMessage.ResolveCommandType, caches a successful result); a name that matches nothing is scanned again for each row carrying it (InternalCommandNameResolver.cs:53-59). - Where it's used:
InternalCommandMessage.cs(2 sites);WebhookDeliveryLane.cs(1 site, naming the command type its lane owns); the lane test harnesses andInternalCommandProcessorTests.cs.
InternalCommandSignal
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandSignal.cs:16· Level 1 · class
- What it is: the production implementation of
IInternalCommandSignal: a wrapper over the sharedWakeUpSignalwake-up primitive, plus an optional second wake that a dedicated lane waits on. - Depends on:
IInternalCommandSignal(implements),WakeUpSignal,IDisposable. - Concept: see
IInternalCommandSignalfor the smart-wait rationale. What this type adds is fan-out without permit theft: aWakeUpSignalholds at most one permit, so two loops waiting on one wake would race for it and one would sleep through the signal; each loop therefore gets its own wake, and oneSignal()sets both. - Walkthrough:
_signal = new WakeUpSignal()(InternalCommandSignal.cs:18) is the shared loop's wake;_laneWake(InternalCommandSignal.cs:19) is null until a lane asks for it;Signal()(InternalCommandSignal.cs:25-29) signals the shared wake and, throughVolatile.Read, the lane wake when one exists;WaitAsync(InternalCommandSignal.cs:32-33) waits on the shared wake only;EnsureLaneWake(InternalCommandSignal.cs:39) andWaitForLaneAsync(InternalCommandSignal.cs:48-49) are the internal lane entry points, both going throughGetOrCreateLaneWake(InternalCommandSignal.cs:58-74), which creates the wake withInterlocked.CompareExchangeand disposes the loser of a creation race;Dispose()(InternalCommandSignal.cs:52-56) disposes both wakes;HasLaneWake(InternalCommandSignal.cs:22) is a test hook. - Why it's built this way: the semaphore mechanics live in
WakeUpSignalso this type and the outbox's own signal share one tested wake-up implementation. The lane creates its wake at construction (EnsureLaneWake), not at its first wait, so a signal sent between the lane starting and its first wait is kept; a host without a lane never allocates the second wake. - Where it's used: registered in
DependencyInjection.Jobs.cs(1 site) as theIInternalCommandSignalimplementation consumed byInternalCommandProcessorandInternalCommandAdministration;InternalCommandLaneProcessortype-tests for it to reach the lane wake (InternalCommandLaneProcessor.cs:205-214); exercised byInternalCommandSignalTests.cs,InternalCommandLaneProcessorTests.csandWebhookDeliveryLaneTests.cs. - ADRs: ADR-114.
InternalCommandLane
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLane.cs:23· Level 4 · record
- What it is: the configuration of one dedicated delivery lane: which command type it drains instead of the shared loop, how a row names its receiver, and the cooldown, concurrency and start budget the lane runs with (
InternalCommandLane.cs:5-10). - Depends on:
IInternalCommand(Application layer, not in this group) through theReceiverKeydelegate. - Concept: the dedicated-lane pattern is taught on
InternalCommandLaneProcessor; this record is its input. - Walkthrough: six positional members (
InternalCommandLane.cs:23-29):Name(thelanemetric tag and log value),CommandType(the stored command name the lane claims),ReceiverCooldown(the configured cooldown after a failed real attempt, which the lane clamps throughInternalCommandLaneProcessor.EffectiveCooldown),ReceiverKey(reads a deserialized command's receiver key; null means no key, so no cooldown and no one-per-receiver rule),MaxConcurrency(rows of one claimed batch run at once on this replica; 1 keeps one row at a time) andBatchStartBudget(how long after a batch's first start new rows may still start, also treated as the longest one attempt can take) (InternalCommandLane.cs:11-22). - Why it's built this way: a lane is defined by data, not by a subclass, so the lane processor holds every lane mechanic once and a feature that wants a lane (the webhook delivery lane) only supplies values and a key reader.
- Where it's used:
InternalCommandLaneProcessor(5 sites);WebhookDeliveryLane(2 sites) builds one; the lane test harnesses andInternalCommandLaneProcessorTests.cs. - ADRs: ADR-114, ADR-142.
InternalCommandDispatcher
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandDispatcher.cs:21· Level 5 · class (static)
- What it is: a static dispatcher with two jobs for a deserialized
IInternalCommand, neither needing compile-time knowledge of the command's concrete type: it resolves and invokes the decoratedICommandHandler<TCommand, Result>, and, when a row is dead-lettered, it runs everyIInternalCommandDeadLetterHandler<TCommand>registered for that command type. - Depends on:
ICommandHandler<TCommand, Result>(Application layer, not in this group),IInternalCommand,IInternalCommandDeadLetterHandler<TCommand>,InternalCommandDeadLetterNotice,IServiceProvider,System.Reflection.MethodInfo,ConcurrentDictionary<TKey,TValue>. - Concept introduced, a compiled-reflection invoker cache.
[Rubric §12: Performance & Scalability]: building one delegate per command type costs a singleMakeGenericMethod+CreateDelegate(InternalCommandDispatcher.cs:23-27); every subsequent row of that type calls the cached delegate directly instead of payingMakeGenericMethodorMethodInfo.Invokeagain. The same shape is used twice:Invokersfor execution andDeadLetterNotifiersfor the dead-letter callbacks (InternalCommandDispatcher.cs:30-31). - Walkthrough:
Invokers(InternalCommandDispatcher.cs:28) caches oneFunc<IServiceProvider, IInternalCommand, CancellationToken, Task<Result?>>per commandType, andDeadLetterNotifiers(InternalCommandDispatcher.cs:31) oneFunc<IServiceProvider, IInternalCommand, InternalCommandDeadLetterNotice, CancellationToken, Task>;InvokeDefinition(InternalCommandDispatcher.cs:34-36) andNotifyDeadLetterDefinition(InternalCommandDispatcher.cs:38-40) reflectively resolve the private static genericInvokeAsyncandNotifyDeadLetterCoreAsyncbynameof, under one inline#pragma warning disable S3011explaining the target is this same class's own private method, so a rename cannot silently break it (InternalCommandDispatcher.cs:33-41);ExecuteAsync(InternalCommandDispatcher.cs:56-63) is the execution entry point:Invokers.GetOrAdd(command.GetType(), BuildInvoker)then invokes;BuildInvoker(InternalCommandDispatcher.cs:122-126) does the one-timeMakeGenericMethod(commandType).CreateDelegate<...>();InvokeAsync<TCommand>(InternalCommandDispatcher.cs:133-148) resolves the handler viaGetService, NOTGetRequiredService(InternalCommandDispatcher.cs:139), so a command with no registered handler on this host resolves tonullrather than throwing.InvokeAsync<TCommand>is notasync: the missing-handler path returnsTask.FromResult<Result?>(null)(InternalCommandDispatcher.cs:142), and otherwise it returns the handler's own task directly with a null-forgiving!(InternalCommandDispatcher.cs:147), becauseTask<T>is not covariant in nullability, so no extra state machine wraps the call.NotifyDeadLetterAsync(InternalCommandDispatcher.cs:76-88) is the dead-letter entry point:DeadLetterNotifiers.GetOrAddwith astaticlambda that closesNotifyDeadLetterDefinitionover the command type (InternalCommandDispatcher.cs:82-86), then invokes;NotifyDeadLetterCoreAsync<TCommand>(InternalCommandDispatcher.cs:90-120) enumeratesGetServices<IInternalCommandDeadLetterHandler<TCommand>>()(InternalCommandDispatcher.cs:98) and awaits each callback in turn, rethrows anOperationCanceledExceptiononly when the token itself is cancelled (InternalCommandDispatcher.cs:104-107), collects any other exception under aCA1031suppression (InternalCommandDispatcher.cs:108-113), and once every callback has run throws oneAggregateExceptionover the collected failures (InternalCommandDispatcher.cs:116-119). With no callback registered the loop runs zero times and the task completes. - Why it's built this way: the doc comment on
ExecuteAsync(InternalCommandDispatcher.cs:50-55) states the rationale for the null-not-throw choice directly: a missing handler is a deployment fact (the owning module is disabled here, or the row was written by a different service), and the caller records that fact on the row instead of treating it as an exception to classify. The dead-letter fan-out collects before it throws (InternalCommandDispatcher.cs:65-69) so one failing callback never stops the others from running; deciding what a failure means is left to the caller, which logs it. - Where it's used:
InternalCommandProcessor(2 sites): itsInvokeAsynccallsExecuteAsyncwhen it executes a claimed row (InternalCommandProcessor.cs:547), and its privateNotifyDeadLetterAsynccallsNotifyDeadLetterAsyncafter a dead letter, in a fresh scope with the row's origin restored (InternalCommandProcessor.cs:699-701). - ADRs: ADR-114.
LaneRow
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLaneProcessor.cs:777· Level 5 · class (private, nested)
- What it is: the lane scheduler's per-row bookkeeping for one claimed
InternalCommandMessage: its receiver key, its running task, and whether and when its real attempt failed. - Depends on:
InternalCommandMessage. - Concept: part of the single-flow scheduler taught on
InternalCommandLaneProcessor: a running row reports back only through these fields and its task, and the scheduler alone acts on them. - Walkthrough:
RowandReceiverKey(InternalCommandLaneProcessor.cs:779,781) are fixed at construction (the key read once per row);Execution(InternalCommandLaneProcessor.cs:784) is the running task, which yields whether the row progressed;Ran(InternalCommandLaneProcessor.cs:787) is set only after the claim renew succeeded;FailedAt(InternalCommandLaneProcessor.cs:793) has a private setter written byMarkFailedAttempt(InternalCommandLaneProcessor.cs:797), the observer the shared row runner calls just before it records a failed attempt. - Why it's built this way: recording the failure instant on the row, rather than reading the clock when the scheduler settles it, opens the cooldown from when the attempt actually failed (
InternalCommandLaneProcessor.cs:495-517), so time the scheduler spends elsewhere never pushes the cooldown end later than the clamp arithmetic assumes. - Where it's used: only inside
InternalCommandLaneProcessorandLaneBatchState.
LaneBatchState
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLaneProcessor.cs:703· Level 6 · class (private, nested)
- What it is: the mutable state of one claimed lane batch while it runs: the waiting and running rows, the receivers that are busy, the progress and charge tallies, and the first failure or shutdown that stopped it.
- Depends on:
LaneRow,ExceptionDispatchInfo. - Concept: part of the scheduler taught on
InternalCommandLaneProcessor. - Walkthrough:
_busyReceivers(InternalCommandLaneProcessor.cs:705) is an ordinalHashSet<string>;Waiting(InternalCommandLaneProcessor.cs:708) keeps claim order andRunning(InternalCommandLaneProcessor.cs:711) is pre-sized tomaxConcurrency;FirstStart(InternalCommandLaneProcessor.cs:714) is the timestamp the start budget counts from;Progressed,ChargedCountandStartsOpen(InternalCommandLaneProcessor.cs:717-723) are the tallies and the gate;FaultandCancellation(InternalCommandLaneProcessor.cs:726,729) hold the captured exceptions;IsReceiverBusy,MarkRunningandMarkFinished(InternalCommandLaneProcessor.cs:732-753) keep the one-row-per-receiver rule;ThrowIfStopped(InternalCommandLaneProcessor.cs:759-767) rethrows the fault, else the shutdown, else throws on a cancellation that stopped the turns before any running row observed it (rows still waiting and none released). - Why it's built this way: capturing exceptions with
ExceptionDispatchInfolets the batch wait for every running row before it rethrows, with the original stack, so a lane never returns while a row of its batch is still running. - Where it's used: only inside
InternalCommandLaneProcessor.
LaneBatch
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLaneProcessor.cs:691· Level 9 · record (private, nested)
- What it is: the fixed facts of one claimed lane batch: the
TenantDataSourceTarget, the batchApplicationDbContext, the source name and the claim token (InternalCommandLaneProcessor.cs:691-695). - Depends on:
TenantDataSourceTarget,ApplicationDbContext. - Concept: a parameter object for the scheduler methods of
InternalCommandLaneProcessor; no pattern of its own. - Walkthrough: built once per claimed batch (
InternalCommandLaneProcessor.cs:284);Targetgives each running row its own tenant scope and context, whileContextis used only for batch-level statements on the scheduling flow (the charges of cooling rows, and the release, which runs once no row is running), never by a running row. - Why it's built this way: separating the batch context from the per-row contexts is what lets rows run concurrently: an EF Core context is not safe for concurrent use.
- Where it's used: only inside
InternalCommandLaneProcessor.
InternalCommandProcessor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:44· Level 13 · class
- What it is: the
BackgroundServiceat the center of the internal-commands job queue: it drains due rows across every relational data source (and tenant) this host owns, executes each viaInternalCommandDispatcher, and records the outcome, using a smart wait instead of a fixed polling interval. - Depends on:
BackgroundService,PollingLoop,IServiceScopeFactory,IOptions<InternalCommandsSettings>(InternalCommandsSettings),IInternalCommandSignal,FrameworkTableTargets,TimeProvider,InternalCommandCycleResult,InternalCommandMetrics,InternalCommandDispatcher,InternalCommandMessage,TenantDataSourceTarget,IDbContextFactory,ApplicationDbContext,InternalCommandLanes(optional, resolved from DI),AmbientOrigin,InternalCommandDeadLetterNotice,System.Diagnostics.ActivitySource. - Concept: the smart-wait polling loop itself now lives in the shared
PollingLoop(cross-reference rather than re-teach): this type supplies its own settings, signal, and per-source work, and PollingLoop runs the loop, computes the wait, and aggregates targets.[Rubric §12: Performance & Scalability]: instead of a fixed poll interval, the loop computes how long until the earliest known upcoming row is due, floors that to avoid a hot loop, caps it at the configured fallback interval, and letsIInternalCommandSignalwake it early.[Rubric §13: Observability & Operability]: poll spans are emitted under their own suppressible activity so an idle fleet's constant polling does not dominate telemetry ingestion, andInternalCommandMetricsis fed every cycle. - Walkthrough: the primary constructor (
InternalCommandProcessor.cs:44-50) takes six required parameters, with target selection delegated to an injectedFrameworkTableTargets; constants:PollActivityName(InternalCommandProcessor.cs:58,"InternalCommandPoll", must stay in sync withOutboxPollFilterProcessorinMMCA.Common.Aspire, which has no project reference here and so duplicates the string),MaxErrorLength(InternalCommandProcessor.cs:61,4000, the column widthLastErroris truncated to),PrincipalAuthenticationType(InternalCommandProcessor.cs:67,"InternalCommand", the auth type stamped on the identity rebuilt from a claimed row);Settings(InternalCommandProcessor.cs:72) is aninternalproperty, not a private field, because a dedicated lane reads the same values;_excludedCommandTypeand_exclusionResolved(InternalCommandProcessor.cs:79,82) cache the lane exclusion;ExecuteAsync(InternalCommandProcessor.cs:86-100) just callsPollingLoop.RunAsync, passingGetTargets().Count > 0ashasTargets,LogNoRelationalSourcesasonNoTargets, a lambda that runsProcessDueCommandsAsyncand maps its result to the(HasMoreWork, EarliestUpcoming)tuplePollingLoopexpects,LogCycleErrorasonCycleError, the configured delay/interval seconds, andsignal.WaitAsyncas the wait delegate (the wait-time computation itself isPollingLoop's, with no wrapper on this type);GetTargets(InternalCommandProcessor.cs:108-109) is a one-line call totableTargets.Relational(DataSource, DatabaseName), recomputed every cycle so a module assembly registered after startup is picked up;ProcessDueCommandsAsync(InternalCommandProcessor.cs:119-135,internalfor direct test invocation) forwards the per-target fan-out toPollingLoop.DrainAllAsync, supplyingProcessSourceAsyncas the per-target delegate andLogSourceErroras the per-source error handler, then publishes the aggregated depth throughInternalCommandMetrics.SetPendingDepth;ProcessSourceAsync(InternalCommandProcessor.cs:141-213) per target opens a DI scope viaCreateTenantScope(InternalCommandProcessor.cs:147), so the tenant is set before theApplicationDbContextis resolved throughIDbContextFactory(same ordering rule as the admin and cleanup types), fetches up toBatchSizerunnable rows viaFetchCandidatesAsync, derives the pending-depth gauge input from that same fetch viaCountPendingAsync(no extra query unless the batch is saturated), publishes the oldest-due-age gauge from the fetch's own first row (no extra query), splits the ordered rows into a due prefix and an upcoming remainder, returns early with no claim when nothing is due or when another replica claimed the whole prefix, otherwise claims the due prefix under a freshclaimTokenand, for each claimed row, first callsRenewClaimAsync(InternalCommandProcessor.cs:198) and skips the row withLogLeaseLostBeforeExecutionwhen the claim is no longer this replica's, else runsExecuteClaimedAsync; it reportsHasMoreDueWorkwhen the due count exactly filledBatchSizeand at least one row progressed (InternalCommandProcessor.cs:210, so a saturated batch triggers an immediate re-poll);FetchCandidatesAsync(InternalCommandProcessor.cs:223-250) runs inside its own suppressibleActivity, queriesAsNoTrackingrows withProcessedOn/DeadLetteredOnnull and no unexpiredClaimedUntil(InternalCommandProcessor.cs:234-237; there is noAttemptsbound in the predicate, because a row that spends its budget is dead-lettered byRecordFailedAttemptAsyncatInternalCommandProcessor.cs:500-506, soDeadLetteredOnis the terminal filter), addsCommandType != excludedonly when a lane is registered (InternalCommandProcessor.cs:239-242), and orders byScheduledOnthenId;CountPendingAsync(InternalCommandProcessor.cs:258-288) short-circuits to the fetched row count when it is belowBatchSize(the fetch already saw the whole backlog) and pays for aCOUNTquery, over the same predicate and exclusion (InternalCommandProcessor.cs:275-278), only when the batch is saturated;GetExcludedCommandType(InternalCommandProcessor.cs:296-306) resolvesInternalCommandLanesonce, on the first cycle, from a fresh scope withGetService, so the exclusion is null (and the predicate unchanged) on a host with no lane;ClaimDueAsync(InternalCommandProcessor.cs:314,internalso the lane reuses it) stampsClaimedUntil = now + LeaseSecondsandClaimedBy = claimTokenon the due prefix in one guardedExecuteUpdateAsync, and on a partial claim re-reads which ids carry this replica's token so only owned rows run;RenewClaimAsync(InternalCommandProcessor.cs:362-376,internal) pushesClaimedUntilforward byLeaseSecondsin a statement guarded onClaimedBy == claimTokenand returns whether a row was updated, which is what makesLeaseSecondsbound one handler rather than the whole batch;ExecuteClaimedAsync(InternalCommandProcessor.cs:388-461,internal) takes an optionalAction? onFailedAttempt(InternalCommandProcessor.cs:394) that it invokes just before a failed attempt is recorded (InternalCommandProcessor.cs:457; the shared loop passes none, the lane uses it to cool a receiver down), and dead-letters a row on the first attempt when its payload throwsJsonExceptionorNotSupportedExceptionon deserialization (InternalCommandProcessor.cs:403-412, reasonpayload_invalid, logged byLogPayloadInvalid), when its type cannot be resolved (type_unresolvable), or when no handler is registered on this host (handler_missing, which passes the already-deserialized command on toDeadLetterAsync,InternalCommandProcessor.cs:443), records lag and duration histograms around the invocation, completes the row on a successfulResult, and otherwise hands off toRecordFailedAttemptAsync(InternalCommandProcessor.cs:475-511,internal, called with the command atInternalCommandProcessor.cs:459), which treats aResult.Failureand a thrown exception alike: dead-letter withattempts_exhaustedonceMaxAttemptsis reached, else schedule a backoff retry. Its trailing optionalIInternalCommand? command(InternalCommandProcessor.cs:484) is forwarded toDeadLetterAsync(InternalCommandProcessor.cs:502); a caller that charges an attempt without executing (a cooling lane row) passes none.DeadLetterAsync(InternalCommandProcessor.cs:626-661) stampsDeadLetteredOnand releases the claim throughStampAsync, adds toInternalCommandMetrics.DeadLetterCounter, and then, only when the stamp matched and a command is available (passed in, or read byTryDeserializeatInternalCommandProcessor.cs:664-674, which returns null onJsonExceptionorNotSupportedException), builds anInternalCommandDeadLetterNoticefrom the row id, reason, truncated message and attempt count (InternalCommandProcessor.cs:656-660) and calls its privateNotifyDeadLetterAsync(InternalCommandProcessor.cs:681-713). That method opens a fresh scope, restores the row's origin withAmbientOrigin.Restore(InternalCommandProcessor.cs:688-695), runsInternalCommandDispatcher.NotifyDeadLetterAsync(InternalCommandProcessor.cs:699-701), rethrows a shutdown cancellation, and logs any other failure throughLogDeadLetterCallbackFailed(InternalCommandProcessor.cs:711) without retrying. Apayload_invalidortype_unresolvablerow has no readable command, so it runs no callbacks.StampAsync(InternalCommandProcessor.cs:729-747) applies the outcome guarded onClaimedBy == claimTokenand returnstruewhen a row was stamped, or logsLogLeaseLostand returnsfalsewhen the lease was lost. - Why it's built this way: the loop, wait-time computation, and per-target aggregation live in
PollingLoopbecause the outbox processor and the dedicated lane run the same loop throughPollingLoop.RunAsync. Dead-letter callbacks run only when this replica's stamp matched, so a replica that lost its lease never notifies for a row another replica now owns, and they run best-effort because the row is already terminal: a failing callback cannot undo or retry the dead letter. An un-suppressed poll span would swamp telemetry for an idle fleet, and aCOUNTon every cycle would be wasted work in the (common) unsaturated case. Cite ADR-114 for the queue itself; the executed handler goes through the same decoratedICommandHandler<TCommand, Result>pipeline any other command uses, per ADR-014. - Where it's used: registered as a hosted service in
DependencyInjection.Jobs.cs(1 site); ADC'sScoreEventSessionsInternalCommand(Conference.Application, 1 site) is a concreteIInternalCommandthis processor drains;InternalCommandProcessorTests.csand the shared test harness exerciseProcessDueCommandsAsyncdirectly;InternalCommandDeadLetterCallbackTests.cs(2 sites) covers the dead-letter callbacks;OutboxPollFilterProcessor.cs(MMCA.Common.Aspire, 2 sites) readsPollActivityNameto filter the matching spans from export;InternalCommandLaneProcessor(5 sites) holds a not-started instance and calls itsinternalrow methods, so a lane row claims, renews, executes, retries and dead-letters through this type's code. - Caveats / not-in-source: the retry backoff (
ComputeRetryBackoffSeconds,InternalCommandProcessor.cs:758-759, forwarding toPollingLoop) and the error rendering after it, through the end of the type atInternalCommandProcessor.cs:850, were not re-read line-by-line for this section. The principal-restore inInvokeAsync(InternalCommandProcessor.cs:522-566) opens a fresh DI scope and callsAmbientOrigin.Restore(InternalCommandProcessor.cs:532), passingrow.UserPermissions(InternalCommandProcessor.cs:536) alongside the roles so persisted permission claims are restored too, and holds the returnedIDisposableinusing var origin, so the restored origin is undone when the call ends rather than left on the ambient context.CompleteAsync(InternalCommandProcessor.cs:569) andScheduleRetryAsync(InternalCommandProcessor.cs:596) are non-asyncmethods that returnStampAsync'sTask<bool>directly, with no state machine of their own; their callers (InternalCommandProcessor.cs:451,InternalCommandProcessor.cs:508) await it and discard the flag, so onlyDeadLetterAsyncacts on a lost lease. - ADRs: ADR-014, ADR-114, ADR-142.
InternalCommandLaneProcessor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.InternalCommands.Processing·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLaneProcessor.cs:51· Level 14 · class
- What it is: a second
BackgroundServicethat drains ONE dedicated lane of the internal-commands table: the rows ofInternalCommandLane.CommandType, which the sharedInternalCommandProcessorexcludes while the lane is registered, so a slow or failing receiver never delays the shared queue (InternalCommandLaneProcessor.cs:17-21). - Depends on:
BackgroundService,InternalCommandProcessor(a not-started instance whose row methods it calls, owned and disposed here),InternalCommandLane,ReceiverCooldowns,IInternalCommandSignal/InternalCommandSignal,PollingLoop,FrameworkTableTargets,InternalCommandsSettings,InternalCommandMetrics,InternalCommandCycleResult, the nestedLaneBatch,LaneBatchState,LaneRowandLaneBatchOutcome,TimeProvider,ExceptionDispatchInfo. - Concept introduced, a dedicated delivery lane with a per-receiver cooldown. One queue table, two drainers: the shared loop skips one command type and a lane process claims only that type, with the same pending predicate, order, batch size and grace period, and the same row code. Inside a claimed batch the lane adds three rules: up to
MaxConcurrencyrows run at once but never two of one receiver; no row starts onceBatchStartBudgethas elapsed since the batch's first start (the rest are released uncharged and are due again at once); and a receiver whose real attempt failed cools down on this replica, during which its rows are charged a failed attempt without being sent, so they keep the normal retry timeline and attempt budget (InternalCommandLaneProcessor.cs:22-42).[Rubric §11: Resilience & Fault Tolerance](assesses how the system contains and recovers from failure): the cooldown is a per-receiver circuit breaker that stops one dead endpoint from consuming the lane's slots, while the clamp inEffectiveCooldownguarantees a receiver that is healthy from the moment a row is scheduled still gets at least one real attempt before that row can dead-letter.[Rubric §13: Observability & Operability]: every lane decision is countable through the lane-tagged instruments onInternalCommandMetrics. - Walkthrough: constants
CoolingDownErrorCode/CoolingDownErrorMessage(InternalCommandLaneProcessor.cs:61,64) form the failure a charged row records, andMinimumJitter(InternalCommandLaneProcessor.cs:67,0.8) is the backoff jitter floor; fields (InternalCommandLaneProcessor.cs:76-87) take the shared processor'sSettings, precompute the shortest retry span and the effective cooldown, build thelanetag and theReceiverCooldowns, and callPrepareLaneWake(InternalCommandLaneProcessor.cs:205-214), which creates the lane wake at construction when the signal is the frameworkInternalCommandSignal;EffectiveCooldown(InternalCommandLaneProcessor.cs:103-116) returns zero (cooldown off) when the shortest retry span or the configured value is zero, elsemin(configured, S - attemptTimeout - 1 s)floored at one second, whereSfromShortestRetrySpan(InternalCommandLaneProcessor.cs:217-229) sumsmin(0.8 x RetryBackoffBaseSeconds x 2^(k-1), MaxRetryBackoffSeconds)over attempts 1 toMaxAttempts - 1;Dispose(InternalCommandLaneProcessor.cs:119-123) disposes the owned processor;ExecuteAsync(InternalCommandLaneProcessor.cs:157-203) logs the start, a clamp warning and a too-short-retry-span warning, then runsPollingLoop.RunAsyncwaiting on the lane wake, or onTask.Delaywith aLogNoLaneWakenotice for any other signal implementation (waiting on it would take the shared loop's permit);ProcessDueCommandsAsync(InternalCommandLaneProcessor.cs:132-150) prunes cooldowns, drains every target and publishes the lane depth gauge;ProcessSourceAsync(InternalCommandLaneProcessor.cs:241-292) mirrors the shared per-target step (its ownFetchCandidatesAsyncatInternalCommandLaneProcessor.cs:598-620uses the shared pending predicate, with noAttemptsbound,InternalCommandLaneProcessor.cs:611-613, filtersCommandType == lane.CommandTypeand tags the poll activity with the lane), claims throughrows.ClaimDueAsync, runs the batch, and re-polls at once when a full batch progressed or charged rows, or when any row was released (InternalCommandLaneProcessor.cs:287-289);RunBatchAsync(InternalCommandLaneProcessor.cs:308-338) loopsStartTurnsAsyncandSettleNextAsyncuntil nothing runs, then releases the unstarted rows and rethrows any stop;StartTurnsAsync(InternalCommandLaneProcessor.cs:346-376) gives turns in claim order while a slot is free, passes over a busy receiver, charges a cooling one throughChargeTurnAsync, and starts the rest, closing turns on shutdown or onceIsStartBudgetSpent(InternalCommandLaneProcessor.cs:379-380);SettleNextAsync(InternalCommandLaneProcessor.cs:402-424) awaitsTask.WhenAnywithout the token (every running row observes it itself), then applies the outcome and frees the receiver;RecordStop(InternalCommandLaneProcessor.cs:430-445) keeps the shutdown, the first fault, and logs later faults;RunRowAsync(InternalCommandLaneProcessor.cs:474-493) opens its own tenant scope and context, renews the claim throughrows.RenewClaimAsync, and executes throughrows.ExecuteClaimedAsyncwithMarkFailedAttemptas the failed-attempt observer;ApplyOutcome(InternalCommandLaneProcessor.cs:502-517) opens the cooldown fromFailedAtor closes it on a successful real attempt;ChargeAsync(InternalCommandLaneProcessor.cs:525-540) records the failed attempt, aResult.FailurecarryingError.Unavailable(CoolingDownErrorCode, CoolingDownErrorMessage)(InternalCommandLaneProcessor.cs:533), throughrows.RecordFailedAttemptAsyncon the batch context, with no renew, scope or handler, and counts the short circuit only after that call returns;ReleaseAsync(InternalCommandLaneProcessor.cs:547-558) clearsClaimedUntilandClaimedByunder the batch claim token in one guardedExecuteUpdateAsync, charging nothing;OpenCooldown(InternalCommandLaneProcessor.cs:564-576) is a no-op when the cooldown is off and counts and logs only a new opening;ReadReceiverKey(InternalCommandLaneProcessor.cs:582-592) returns null for a row that cannot be deserialized, which the shared runner then dead-letters as usual. - Why it's built this way: reusing the shared processor's
internalrow methods keeps one implementation of claiming, renewing, executing, retrying and dead-lettering, so a lane row and a shared row cannot drift. Every scheduling decision and every cooldown read or write happens on one logical flow and running rows report back only through their task (InternalCommandLaneProcessor.cs:294-307), which is whyReceiverCooldownsneeds no locking. Rows run on their own scopes and contexts because a context is not safe for concurrent use. The design is recorded in ADR-142, on top of the queue in ADR-114. - Where it's used:
WebhookDeliveryLane(3 sites) is the one lane in Common;InternalCommandLaneandInternalCommandSignalreference it in doc comments; exercised byInternalCommandLaneProcessorTests.cs,InternalCommandLaneConcurrencyTests.cs,WebhookDeliveryLaneTests.cs, the lane test and database harnesses, and the PostgreSQL and SQL Server Testcontainers tiers. - Caveats / not-in-source: the hosted-service registration of the lane (the call that adds it and
InternalCommandLanesto DI) lives withWebhookDeliveryLane.csand was not re-read for this section;CountPendingAsync(InternalCommandLaneProcessor.cs:623) was read only through its saturation short-circuit and predicate (InternalCommandLaneProcessor.cs:630-645), which match the fetch. - ADRs: ADR-114, ADR-142.
GroupedCount<TKey>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:185· Level 0 · record (private sealed, nested)
- What it is: a two-property carrier for one
GROUP BYrow: the grouping key and the number of rows carrying it. It is declaredprivate sealed record classinsideEFReadRepository<TEntity, TIdentifierType>, so it exists only for the lifetime of one query translation and is invisible to every caller (EFReadRepository.cs:182-185). - Depends on: nothing first-party.
TKeyis the caller's grouping key type, constrained tonotnullat theCountByAsync<TKey>declaration (EFReadRepository.cs:136). - Concept introduced, a named projection target so the provider can translate the grouping.
[Rubric §12, Performance and Scalability]assesses whether aggregation happens in the database rather than after materialization.CountByAsynccomposesquery.GroupBy(keySelector).Select(group => new GroupedCount<TKey>(group.Key, group.Count()))(EFReadRepository.cs:145-149), so theCOUNTand theGROUP BYare both pushed to SQL and only one row per key comes back. The reason a named type appears here at all rather than an anonymous type or a tuple is translatability: EF Core needs a constructor-shaped projection it can bind by parameter name, and a positional record gives it exactly that with a single line of code. The result is flattened into anIReadOnlyDictionary<TKey, int>immediately afterwards (:146), so the record never escapes the method. - Walkthrough
Key(EFReadRepository.cs:185): the grouping key, projected fromgroup.Key.Value(EFReadRepository.cs:185): theintrow count, projected fromgroup.Count().- The record has no methods of its own. Being a positional
record class, it gets value equality and aDeconstructfree, neither of which the one call site uses; the shape is the whole point.
- Why it's built this way: nesting it privately inside the repository keeps a purely mechanical translation helper out of the assembly's type surface, while still giving EF a real named type to bind to. It is the counterpart of
GroupedSum<TKey>, and the two are deliberately separate rather than one genericGrouped<TKey, TValue>, because theintanddecimalaggregate shapes translate through different provider paths. - Where it's used: only in
EFReadRepository.CountByAsync<TKey>(EFReadRepository.cs:147, flattened at:146). The public capability it backs is consumed in MMCA.ADC byBookmarkCountService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/UserSessionBookmarks/Services/BookmarkCountService.cs:27) andGetAttendanceStatsHandler(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/CheckIns/UseCases/GetAttendanceStats/GetAttendanceStatsHandler.cs:32), and covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/EFReadRepositoryReadSurfaceTests.cs.
GroupedSum<TKey>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:190· Level 0 · record (private sealed, nested)
- What it is: the summing twin of
GroupedCount<TKey>: oneGROUP BYrow carrying the key and thedecimaltotal for that key (EFReadRepository.cs:187-190). Same nesting, same privacy, same single-method lifetime. - Depends on: nothing first-party; see
GroupedCount<TKey>for the concept. - Concept: introduced by
GroupedCount<TKey>. What is worth reading here is the element selector on the grouping.SumByAsynccallsquery.GroupBy(keySelector, sumSelector)with two expressions and thengroup.Sum()with none (EFReadRepository.cs:173-177). The comment at:165-167explains the choice: choosing the summed column inside the grouping keeps the caller's expression tree intact all the way to the provider, whereas summing over the grouping with a separately supplied expression would need that tree spliced in by hand.[Rubric §12, Performance and Scalability]again: the whole aggregation is one statement. - Walkthrough
Key(EFReadRepository.cs:190): the grouping key.Value(EFReadRepository.cs:190): thedecimaltotal, projected fromgroup.Sum()over the element-selected column.- Flattened to
IReadOnlyDictionary<TKey, decimal>atEFReadRepository.cs:179.
- Why it's built this way: identical rationale to its twin.
decimalrather than a generic numeric parameter matches the framework's money and points columns, which are the values callers actually total. - Where it's used: only in
EFReadRepository.SumByAsync<TKey>(EFReadRepository.cs:175). The capability is consumed in MMCA.ADC byGetLeaderboardHandler(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Points/UseCases/GetLeaderboard/GetLeaderboardHandler.cs:55) and covered byEFReadRepositoryReadSurfaceTests.cs.
LookupRow<TId, TName>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:747· Level 0 · class (internal sealed)
- What it is: the intermediate row a non-string lookup projection materializes: the entity's identifier plus the name property carried in its own CLR type, rather than pre-formatted to a string (
EFReadRepository.cs:739-754). Declared at file scope inEFReadRepository.cs, alongside the class it serves, rather than nested private the wayGroupedCount<TKey>andGroupedSum<TKey>are:EFReadRepository<TEntity, TIdentifierType>'sExecuteRawLookupAsync<TName>ispublic staticand needsLookupRow<TId, TName>in its own signature, which aprivatenested type could not appear in. - Depends on: nothing first-party.
TIdandTNameare the caller's identifier and raw name types, closed over byEFReadRepository<TEntity, TIdentifierType>'sBuildLookupSelector(EFReadRepository.cs:353) andExecuteRawLookupAsync<TName>(:282). - Concept, why the projection stops short of a string.
[Rubric §12, Performance and Scalability]assesses whether a translation failure is designed out rather than caught after the fact.GetAllForLookupAsync's selector used to callToString()inside theSelectfor a non-string name property, which has no server-side translation for a value-object property (anEmail, say): appending it to the projection threwInvalidOperationExceptionfor the whole query and surfaced as an HTTP 500 on a propertyQueryFieldServicehad already approved as sortable.LookupRow<TId, TName>is the fix: the projection stops at the raw value, in whatever CLR type EF materializes it through the property's own value converter, and the formatting to a display string happens in memory afterwards, inExecuteRawLookupAsync<TName>, whereToString()is plain C# rather than an expression tree a provider has to translate. - Walkthrough
Id(EFReadRepository.cs:750): the entity identifier,TId, defaulted todefault!like the other lightweight projection carriers in this file.Name(EFReadRepository.cs:753): the raw name value,TName?, exactly as the provider materialized it, with no coalescing or formatting applied at this stage.
- Why it's built this way: a generic carrier rather than one record per name type is what lets
BuildLookupSelectorbuild the projection once per(TEntity, TName)pair by reflection (Expression.MemberInitoverExpression.New(rowType),EFReadRepository.cs:353-357) without a compile-time-known type for every possible name property;sealedand two auto-properties keep it a pure carrier with nothing else to reason about. - Where it's used: only inside
EFReadRepository.cs.BuildLookupSelectorclosesLookupRow<,>over(TIdentifierType, nameAccess.Type)for a non-string name property (EFReadRepository.cs:353);ExecuteRawLookupAsync<TName>takes the resultingExpression<Func<TEntity, LookupRow<TIdentifierType, TName>>>as its selector parameter (:282), projects, orders and caps with it, then formats each row'sNameto the returnedBaseLookup<TIdentifierType>(:292-296). - Caveats / not-in-source: no test file targets
LookupRow<TId, TName>by name; it is exercised indirectly throughEFReadRepositoryLookupProjectionTests.cs(listed amongEFReadRepository<TEntity, TIdentifierType>'s usage sites) whenever a non-string name property is looked up.
ValueHolder<T>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/KeysetQueryBuilder.cs:291· Level 0 · class (private sealed, nested)
- What it is: a single-field carrier declared
private sealed class ValueHolder<T>(T value)insideKeysetQueryBuilder, whose only member is a get-onlyValueproperty assigned from the primary constructor (KeysetQueryBuilder.cs:291-295). - Depends on: nothing.
Tis the caller's boundary-value type, supplied byKeysetQueryBuilder.Capture. - Concept introduced, making a literal look like a captured local so EF parameterizes it.
[Rubric §12, Performance and Scalability]assesses whether a hot query path reuses compiled plans instead of minting a fresh one per call. A bareExpression.Constantis translated by every EF provider as an inlined literal, which is wrong for a keyset cursor boundary: the value changes on every page of every cursor, so each page would get its own statement text, missing EF's compiled-query cache and filling the server's plan cache with thousands of single-use plans. Reading the value off a member of a constant holder instance is the same expression shape the C# compiler emits for a captured local, so EF's parameter extraction evaluates the subtree once and binds the result as a query parameter instead, leaving the statement text identical across pages. - Walkthrough
Value(KeysetQueryBuilder.cs:294): the one carried value, assigned once from the constructor parameter, never mutated.
- Why it's built this way: a whole class for one field is deliberate rather than minimal:
KeysetQueryBuilder.Captureneeds aMemberExpressionreading a property off aConstantExpression, and a generic single-property class is the smallest shape that produces one, closed over the boundary's declared type viaMakeGenericType. - Where it's used: only by
KeysetQueryBuilder.Capture(value, type), which constructs one instance throughActivator.CreateInstanceand returnsExpression.Propertyreading itsValuemember; bothBuildSeekPredicateboundary constants (the identifier boundary and the sort-key boundary) go throughCapturerather than a bareExpression.Constant. - Caveats / not-in-source: private and nested, so it has no existence outside
KeysetQueryBuilder; the null-boundary comparisons deliberately bypass it and keep realExpression.Constant(null, ...)nodes, becauseIS NULLis a shape EF must see as a constant, not a parameterized value.
WakeUpSignal
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Polling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Polling/WakeUpSignal.cs:16· Level 0 · class
- What it is: the shared wake-up primitive behind both queue signals: an internal, single-slot
SemaphoreSlim(0, 1)wrapper used purely as a flag, not a resource lock. - Depends on:
System.Threading.SemaphoreSlim,IDisposable. - Concept: the semaphore is capped at one permit because a drain cycle empties a whole batch per pass, so a burst of signals carries no more information than a single one; extracting it here lets both queue signals share the exact same wake-up mechanics instead of each owning a copy.
- Walkthrough:
_semaphore = new(0, 1)(WakeUpSignal.cs:27);Signal()(WakeUpSignal.cs:30-40) releases the semaphore and swallowsSemaphoreFullException, because a wake-up already pending means "one batch drains everything: nothing to add";WaitAsync(timeout, cancellationToken)(WakeUpSignal.cs:37-47) awaits the semaphore with the given timeout and re-throwsOperationCanceledExceptiononly when the token itself requested cancellation, so shutdown propagates but a plain timeout returns normally;Dispose()(WakeUpSignal.cs:50) disposes the semaphore. - Why it's built this way: pulling this out of
InternalCommandSignalmeans the internal-commands queue and the outbox share one tested wake-up implementation instead of two independent copies of the same semaphore dance. - Where it's used: wrapped by
InternalCommandSignal(2 sites) and byOutboxSignal(2 sites,MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxSignal.cs).
UpdatePropertySetterBuilder<TEntity>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/UpdatePropertySetterBuilder.cs:14· Level 1 · class (internal sealed)
- What it is: the recorder that sits behind the persistence-agnostic
IUpdatePropertySetter<TEntity>. Application code describes a set-based update as a series ofSet(property, value)calls; this class collects those calls as deferred actions and replays them onto EF Core 10'sUpdateSettersBuilder<TSource>at the momentExecuteUpdateAsyncruns (UpdatePropertySetterBuilder.cs:7-14). - Depends on:
IUpdatePropertySetter<TEntity>(the Application-layer contract it implements, declared atMMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IUpdatePropertySetter.cs:13),System.Linq.Expressionsfor the property selectors, and EF Core'sMicrosoft.EntityFrameworkCore.Query.UpdateSettersBuilder<TSource>(UpdatePropertySetterBuilder.cs:1-3). - Concept introduced, the adapter that keeps EF Core out of the Application layer.
[Rubric §3, Clean Architecture]assesses whether the inner layers stay free of infrastructure types, and[Rubric §2, Design Patterns]assesses whether a named pattern is used where it earns its place. EF'sExecuteUpdateAPI takes a lambda over an EF-owned builder type. Exposing that lambda directly would putMicrosoft.EntityFrameworkCorein the signature of every Application-layer command that wants a set-based update, which is precisely the dependency the layer rules forbid. The fix is a two-step: the Application layer sees onlyIUpdatePropertySetter<TEntity>, and this Infrastructure class buffers each described assignment as anAction<UpdateSettersBuilder<TEntity>>(UpdatePropertySetterBuilder.cs:16) that is not executed until EF hands over a real builder. The expression trees themselves cross the boundary unchanged, becauseExpression<Func<TEntity, TProperty>>is a BCL type, not an EF type.[Rubric §12, Performance and Scalability]also applies:ExecuteUpdateis the set-based path that updates matching rows in one statement without loading or tracking them, which is what makes the adapter worth having at all. - Walkthrough
- Two fields, both collection-initialized:
_assignmentsholds the deferred replay actions in call order, and_assignedPropertiesis the set of top-level property names already assigned (UpdatePropertySetterBuilder.cs:16-17). Set<TProperty>(property, value)(UpdatePropertySetterBuilder.cs:20-28) is the constant-value overload. It null-guards the selector, records the property name, appends a closure callingbuilder.SetProperty(property, value), and returnsthisso calls chain fluently.Set<TProperty>(property, valueFactory)(UpdatePropertySetterBuilder.cs:31-40) is the computed-value overload: the second argument is itself an expression over the entity, which is howSetProperty(x => x.Count, x => x.Count + 1)style updates are expressed. Same guards, same recording, same fluent return.IsEmpty(UpdatePropertySetterBuilder.cs:43) reports whether anything was described at all.EFRepository<TEntity, TIdentifierType>turns atruehere into anArgumentExceptionrather than issuing a no-op UPDATE (EFRepository.cs:112-113).SetsProperty(propertyName)(UpdatePropertySetterBuilder.cs:49) is the audit-stamping guard: it answers "did the caller already assign this column?" so the automaticLastModifiedOnandLastModifiedBystamp never overwrites an explicit value.Apply(builder)(UpdatePropertySetterBuilder.cs:52-58) is the replay: iterate the recorded actions, invoke each against EF's real setters builder. It is passed as a method group straight into EF (EFRepository.cs:133).TrackPropertyName(UpdatePropertySetterBuilder.cs:60-66) only records a name when the selector body is aMemberExpression, which is the shape of a simplee => e.Propertylambda. A more complex selector contributes no name, soSetsPropertyanswersfalsefor it and the audit stamp is applied. That is the safe direction of the two.
- Two fields, both collection-initialized:
- Why it's built this way: recording rather than adapting live is what makes the type useful in two directions at once. The Application layer never sees EF, and the repository gets a chance to inspect and augment the described update before it is issued, which is exactly what the audit stamping in
EFRepository<TEntity, TIdentifierType>needs.internal sealedkeeps the class invisible outside the Infrastructure assembly: consumers only ever hold the interface. The repository plus specification contract this member belongs to is recorded in ADR-055. - Where it's used: constructed once per call in
EFRepository.ExecuteUpdateAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:110), fed by the caller'sAction<IUpdatePropertySetter<TEntity>>(:114), interrogated for the audit stamp (:120,:126), and finally replayed into EF (:131). The profiled path forwards the same delegate throughEFRepositoryDecorator<TEntity, TIdentifierType>(EFRepositoryDecorator.cs:48-53). - Caveats / not-in-source: the framework's own set-based updates in the outbox and the scheduler call EF's
ExecuteUpdateAsyncdirectly on aDbSetrather than through this abstraction (for exampleMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxFinalizer.cs:41), which is legitimate because those types are already inside Infrastructure. The abstraction exists for the Application layer, so do not read those call sites as the intended usage pattern.
QueryTags
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/QueryTags.cs:18· Level 2 · class (internal static)
- What it is: the shared helper that composes and applies EF Core query tags (
TagWith), so a generated SQL statement can be traced back to the use case and the query-builder detail that produced it (QueryTags.cs:18-68). - Depends on:
QueryTagScopefor the ambient use-case half of the tag (Tag<TEntity>,QueryTags.cs:42), and EF Core'sIQueryable<T>.TagWithextension. No other framework types. - Concept introduced, a two-half tag composed from an ambient scope and a local detail.
[Rubric §13, Observability and Operability]assesses whether a slow query in a provider's query store can be traced back to the code that issued it. A tag has two independent halves: the ambient use case (set byQueryTagScopearound a handler) and a detail the query-building code itself knows, such as which specification or which keyset sort ran.Compose(QueryTags.cs:55-67) handles all four presence combinations, joining both halves with a space when both are known, using whichever one is known alone, and returningnullwhen neither is (:60-66). Thenullcase is deliberate rather than an omission:Tag<TEntity>(:39-47) checks for it explicitly because EF throws on an empty tag, so an untagged query is the correct outcome, not a bug to guard against (:44-46). - Walkthrough
HandlerPrefix = "handler:"(QueryTags.cs:21),SpecificationPrefix = "spec:"(:24), andKeysetPrefix = "keyset:"(:27) are the threeinternal constprefixes that make a tag's origin recognizable at a glance in a query store.Tag<TEntity>(query, detail)(QueryTags.cs:39-47) composes the ambient scope with the caller's already-prefixeddetailand appliesTagWithwhen the result is non-null, otherwise returns the query untouched.Compose(handlerName, detail)(QueryTags.cs:55-67) is the pure string-composition function, kept separate fromTagso it is trivially unit-testable without a realIQueryable.
- Why it's built this way: centralizing composition here is what lets
SpecificationEvaluatorandKeysetQueryBuildertag their queries with the same prefix vocabulary rather than each inventing its own string format, so a query store search forspec:orkeyset:finds every occurrence regardless of which builder produced it. - Where it's used:
SpecificationEvaluator.Applytags withSpecificationPrefix + specification.GetType().Name(SpecificationEvaluator.cs:52-54);KeysetQueryBuilder.ApplyOrderingtags withKeysetPrefix + (sortProperty?.Name ?? "Id")(KeysetQueryBuilder.cs:71);EFReadRepository<TEntity, TIdentifierType>reaches both through the two composition helpers rather than callingQueryTagsdirectly. - Caveats / not-in-source:
internal, so it is not part of the framework's public surface; a host wanting its own tag vocabulary composes its own prefix strings before callingTagWithdirectly.
PollingLoop
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Polling·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Polling/PollingLoop.cs:12· Level 3 · class (static)
- What it is: the smart-wait polling loop extracted out of the outbox and internal-commands processors so both share one implementation: run cycles until cancelled, re-poll immediately when a cycle reports more work, otherwise wait on a signal bounded by a computed smart wait; plus the retry-backoff and per-source fan-out helpers both processors also share.
- Depends on:
System.TimeProvider,TenantDataSourceTarget. - Concept: this is the smart-wait loop, backoff formula, and per-target fan-out originally described under
InternalCommandProcessor/OutboxProcessor, now factored into one shared static class so the two processors cannot drift out of sync on the same shape.[Rubric §12: Performance & Scalability]still applies here directly:ComputeWaitTimeis what turns a fixed poll into a smart wait, andComputeRetryBackoffSeconds's jitter (PollingLoop.cs:206) is what keeps a batch that failed together from retrying in lockstep against the same dependency. - Walkthrough:
StartupDelay(PollingLoop.cs:18, 5 seconds),MinimumWait(PollingLoop.cs:21, 1 second) andReadinessMargin(PollingLoop.cs:29, 50 milliseconds) are the shared constants;RunAsync(PollingLoop.cs:48-101) waitsStartupDelay, returns viaonNoTargetswhenhasTargets()is false, then loops callingrunCycle, re-polling immediately onHasMoreWorkand otherwise awaitingwaitForSignalforComputeWaitTime's result, with a cycle exception reported throughonCycleErrorand treated as no pending work (the broad catch carries a scopedCA1031suppression,PollingLoop.cs:79-81, because one failed cycle must not stop the loop for the life of the process);ComputeWaitTime(PollingLoop.cs:117-134) returns the fallbackpollingIntervalwhenearliestUpcomingis null, otherwise computesearliestUpcoming + processingDelay - utcNowand branches on it (PollingLoop.cs:128-131): a row already due (zero or negative) waitsMinimumWait, so a row left for a later cycle cannot hot-loop the processor, while a row not due yet waits until its due instant plusReadinessMargin, so the floor never pushes it past that instant; either result is capped atpollingInterval. The margin exists because eligibility is a strict< cutoffcomparison and the signal wait truncates its timeout to whole milliseconds, so waking at the exact instant can still find the row ineligible (the doc atPollingLoop.cs:23-28);DrainAllAsync(PollingLoop.cs:147-185, takes anIReadOnlyList<TenantDataSourceTarget>(PollingLoop.cs:148) plus adrainSourcedelegate) aggregatesHasMoreWork(OR),EarliestUpcoming(min) and a summedPendingDepthacross targets, isolating one source's exception viaonSourceErrorfrom the others (PollingLoop.cs:174-181, again under a scopedCA1031suppression);ComputeRetryBackoffSeconds(PollingLoop.cs:197-209) computesbase * 2^(attempts-1), clamps the exponent at16beforeMath.Pow(PollingLoop.cs:202, so a future settings change cannot overflow it), applies[0.8, 1.2]jitter BEFORE the cap so a capped backoff lands exactly at the ceiling (PollingLoop.cs:206), then caps atcapSeconds;ComputeCircuitOpenBackoffSeconds(PollingLoop.cs:219-220) is the lease for a row a circuit breaker rejected: the break duration plus up to a quarter of it, capped atcapSeconds, so the rejected rows of a batch do not all become claimable the instant the circuit half-opens. Both backoffs draw their jitter from the privateNextJitter(PollingLoop.cs:223,Random.Shared.NextDouble()), the one place theCA5394suppression for a non-cryptographic random lives. - Why it's built this way: the processors (internal-commands, its per-lane processor, outbox) had nearly identical loop, wait-time, drain, and backoff code; extracting it here is a straight de-duplication, not a new abstraction over a different concept, so each caller keeps its own settings, signal, and per-source work delegate and passes them in as parameters.
- Where it's used:
OutboxProcessor(RunAsync,ComputeWaitTime,DrainAllAsync,ComputeCircuitOpenBackoffSecondsandComputeRetryBackoffSecondsatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:138,:144,:151,:171,:660,:1104,:1108),InternalCommandProcessor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandProcessor.cs:87,:117,:138,:702), andInternalCommandLaneProcessor(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Processing/InternalCommandLaneProcessor.cs:66,:136,:189). The wait-time branch is covered byOutboxProcessorWaitTests.csunderMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Outbox/Processing/.
SpecificationEvaluator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/SpecificationEvaluator.cs:21· Level 4 · class (internal static)
- What it is: the one place a specification becomes an
IQueryable<T>. It always applies the specification's criteria, and when the specification is aQuerySpecification<TEntity, TIdentifierType>it also applies that specification's includes, ordering, and paging (SpecificationEvaluator.cs:11-21). - Depends on:
ISpecification<TEntity, TIdentifierType>andQuerySpecification<TEntity, TIdentifierType>for the input shape,OrderExpressionfor each ordering key,IBaseEntity<TIdentifierType>as the entity constraint (SpecificationEvaluator.cs:44),QueryTagsfor tagging the query with the specification's type name, EF Core'sIncludeandAsSplitQueryextensions, plusSystem.ReflectionandSystem.Collections.Concurrentfor the two caches (:1-6). - Concept introduced, the evaluator half of the specification pattern.
[Rubric §2, Design Patterns]assesses whether patterns are implemented completely rather than named; the specification pattern has two halves, a declarative object describing what to select and an evaluator that turns it into a provider query, and this class is the second half.[Rubric §3, Clean Architecture]also applies: the specification types live in the Domain layer and know nothing about EF, so all EF knowledge is concentrated here. The most important thing to internalize is stated in the class doc atSpecificationEvaluator.cs:15-19, and it is a boundary, not an omission. Tracking and soft-delete scope are deliberately not applied here. Those two choices select the base queryable (TableversusTableNoTracking, with or without the named soft-delete filter dropped), which only a repository holding theDbContextcan do. The evaluator composes on top of whatever base it is handed, which is whyBaseQueryForlives inEFReadRepository<TEntity, TIdentifierType>(EFReadRepository.cs:573-582) and not here. - Walkthrough
Apply<TEntity, TIdentifierType>(source, specification, applyShape = true)(SpecificationEvaluator.cs:40-69) is the entry point. It appliesspecification.Criteria, then tags the resulting query throughQueryTagswithSpecificationPrefix + specification.GetType().Name(:52-54), tagging first so the label survives whatever shape composes on top of it, because EF carries tags on the query rather than on the operator they were attached to (:50-51). It then returns early when eitherapplyShapeis false or the specification is not aQuerySpecification(:56-57). Otherwise it layers includes, then ordering, thenSkipwhen it is a positive integer, thenTake(:59-66). Skip before Take, ordering before both: that is the only order in which paging is meaningful.- The
applyShapeparameter earns its own doc paragraph (SpecificationEvaluator.cs:30-35) and it is a real correctness argument, not a micro-optimization. Aggregate reads such as count and exists passfalse, because joining includes in to count rows costs a join per navigation, and counting "page 3 of the matches" is never what a caller means. ApplyIncludes<TEntity>(query, includes)(SpecificationEvaluator.cs:87-104) applies each non-blank dot-separated path with EF's string-basedInclude(:97-101), tracking whether any path touches a collection navigation, and switches the whole query toAsSplitQuery()when one does (:103). That is the cartesian-explosion guard: two sibling collections loaded in one JOIN multiply rows, so EF issues separate queries instead.ApplyOrdering<TEntity>(query, orderBy)(SpecificationEvaluator.cs:115-129) walks the ordering keys in order and delegates each toApplyOrderingStep, passingisFirst: i == 0(:123-126). An empty list leaves the query untouched, which preserves any ordering the caller already applied (:108-109).ApplyOrderingStep<TEntity>(query, keySelector, descending, isFirst)(SpecificationEvaluator.cs:140-160) is where the untypedLambdaExpressionis bound back to a concrete key type. The four-way(isFirst, descending)switch picks one ofOrderBy,OrderByDescending,ThenBy, orThenByDescending(:150-156), then closes the cachedMethodInfoover(TEntity, keySelector.ReturnType)and invokes it (:158-159). This is the memberKeysetQueryBuilderreuses, which is why the specification path and the keyset path can never produce differently-shaped ORDER BY clauses.- Two static caches keep the reflection cost off the hot path.
OrderingMethods(SpecificationEvaluator.cs:166-180) resolves the four two-generic-argument, two-parameterQueryableoverloads exactly once at type initialization; the per-call cost is a dictionary hit plus aMakeGenericMethod.CollectionIncludeCache(:187) is aConcurrentDictionarykeyed by(entity type, include path)memoizing the collection-navigation walk inIsCollectionNavigationPath(:189-207). IsCollectionNavigationPathwalks the path segment by segment. An unknown segment returnsfalseand defers to EF's own include validation rather than guessing (SpecificationEvaluator.cs:196-197); a segment whose type isIEnumerablebut notstringreturnstrue(:200-201). Thestringexclusion matters:stringimplementsIEnumerable<char>and would otherwise force every string-valued path into split-query mode.
- Why it's built this way:
internal staticwith no state beyond two caches makes it trivially safe to share across every repository instance in the process. The<remarks>atSpecificationEvaluator.cs:77-82records the deliberate consolidation:EFReadRepository.ApplyIncludesandEFQueryableExecutor.Include(whichEntityQueryPipelinecalls per navigation) both delegate here rather than duplicating the logic, so the string-include, specification, and query-pipeline paths cannot drift apart. The overall contract is ADR-055; the expectation that a specification's criteria translate on more than one engine is ADR-018. - Where it's used: only from this group's infrastructure types.
EFReadRepository<TEntity, TIdentifierType>callsApplyfromFirstOrDefaultAsync(specification)(EFReadRepository.cs:126-127), fromCountAsync(specification)withapplyShape: false(:453-454), fromQueryForwithapplyShape: false(:591), from bothListAsyncoverloads (:605-606,:622-623), and fromGetPageByCursorAsyncagain withapplyShape: false(:664); itsApplyIncludesis a thin forwarder to this class (:560-563).EFQueryableExecutorroutes its per-navigationIncludethroughApplyIncludes(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EFQueryableExecutor.cs:22), which is howEntityQueryPipelinereaches the same split-query heuristic (the comment atMMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:132).KeysetQueryBuildercallsApplyOrderingStepthree times (KeysetQueryBuilder.cs:77,:80,:81). Covered bySpecificationEvaluatorTests.csandSplitQueryHeuristicTests.csunderMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/, and by.../Persistence/Repositories/Read/EFReadRepositorySpecificationTests.cs.
KeysetQueryBuilder
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/KeysetQueryBuilder.cs:22· Level 5 · class (internal static)
- What it is: the expression-tree factory for keyset (also called seek) pagination. It resolves the requested sort column, builds the
(sortKey, Id)ordering, builds the seek predicate that selects the rows strictly after a cursor's boundary row, and renders and parses cursor values with invariant culture (KeysetQueryBuilder.cs:9-22). - Depends on:
IBaseEntity<TIdentifierType>for theIdmember it orders and seeks on (KeysetQueryBuilder.cs:74,:128),SpecificationEvaluatorfor the actualOrderByandThenBycalls,QueryTagsfor tagging a keyset page in the generated SQL, its own privateValueHolder<T>for parameterizing cursor boundary values, and the BCL:System.Linq.Expressions,System.Reflection,System.Globalization, andSystem.ComponentModel.TypeDescriptor(:1-5). - Concept introduced, keyset pagination and why the tie-break is mandatory.
[Rubric §12, Performance and Scalability]assesses whether reads stay cheap as the table grows, and[Rubric §9, API and Contract Design]assesses whether the paging contract a client sees is honest. Offset paging (OFFSET 40000 ROWS FETCH NEXT 20) makes the database count past every skipped row, so page 2000 costs far more than page 20. Keyset paging instead orders by(sortKey, Id)and asks for the rows after the last row of the previous page, which the database can satisfy with a single index seek regardless of depth. The class doc states the second half of the idea, which is the part people skip (KeysetQueryBuilder.cs:12-15): the tie-break onIdis what makes the order total. Without it, two rows sharing a sort value can swap places between requests and be returned twice or never. The restriction to exactly one sort key is also deliberate and documented (:18-20): multi-key keyset paging needs a comparison whose size grows quadratically in the key count, and every provider translates it differently. - Walkthrough
TryResolveSortProperty<TEntity>(sortColumn, out property)(KeysetQueryBuilder.cs:35-47) returnstruewith anullproperty when no column was requested (paging byIdalone,:39-40), and otherwise does a case-insensitive public-instance property lookup (:42-44). Afalsereturn means the client named something that does not exist, which the caller turns into a validation failure rather than an exception.ApplyOrdering<TEntity, TIdentifierType>(query, sortProperty, descending)(KeysetQueryBuilder.cs:62-82) first tags the query throughQueryTagswithKeysetPrefix + (sortProperty?.Name ?? "Id")(:71), so every keyset page, specification-driven or not, names itself in the generated SQL. It then builds ane => e.Idselector from the shared parameter (:73-74), then either orders byIdalone in the requested direction (:76-77) or orders by the sort key in the requested direction and then byIdalways ascending (:79-81). The identifier tie-break always ascends, which is exactly what the seek predicate assumes.BuildSeekPredicate<TEntity, TIdentifierType>(sortProperty, sortValue, lastId, descending, nullsSortFirstAscending = true)(KeysetQueryBuilder.cs:118-180) is the heart of the type. The last parameter (:123) says where the engine puts nulls: SQL Server and SQLite sort them first ascending and last descending, PostgreSQL the reverse (ASC NULLS LAST,DESC NULLS FIRST), as the remarks at:102-106state. Before any null handling the method folds the engine and the page direction into one flag,nullsFirst = nullsSortFirstAscending ? !descending : descending(:143-144), meaning "null keys come before the non-null ones in this page's traversal order". It then has four branches:- No sort key (
:131-136): the predicate isId > lastId, flipped to<when the page descends, because there the identifier is the sort key. - Null boundary on a non-nullable key (
:148-152): impossible by construction, so it degrades to the plain id seek rather than emitting a comparison against null. - Null boundary on a nullable key (
:154-162): stated explicitly rather than left to SQL. Where nulls come first in the traversal, what remains is "any non-null value, or a null with a larger id"; where nulls come last, what remains is "a null with a larger id" (:156-160). The remarks at:94-101give exactly this reasoning, and the reason it is needed: SQL comparisons against NULL are unknown and would silently drop rows. - Normal boundary (
:165-179): the classic compositesort > v OR (sort == v AND Id > lastId)(:166-168), with the sort half flipped to<for a descending page. When the key is nullable and nulls come last in the traversal (!nullsFirst), an extrasort == null OR (...)is prepended (:170-177), because a comparison against null is unknown and the nulls still ahead would otherwise vanish. On SQL Server and SQLite that is the descending page; on PostgreSQL it is the ascending one.
- No sort key (
- Both boundary constants, the identifier (
:129) and the sort key (:165), are built through the privateCapture(value, type)(:280-286, reasoning in the remarks at:263-276) rather than a bareExpression.Constant.Capturewraps the value in aValueHolder<T>instance and returns aMemberExpressionreading itsValueproperty, which is the same shape the compiler emits for a captured local, so EF's parameter extraction binds it as a query parameter instead of inlining it as a literal. The null-boundary comparisons deliberately keep realExpression.Constant(null, ...)nodes instead, becauseIS NULLis a shape, not a value that changes per page. ToInvariantString(value)(KeysetQueryBuilder.cs:189-199) renders a value for the cursor. The four date and time types use the round-trip"O"format specifically so a cursor never loses sub-second precision and re-seeks onto the wrong row (:192-195); strings pass through (:196); anythingIFormattablegets invariant formatting (:197); everything else falls back toToString()(:198).TryFromInvariantString(targetType, text, out value)(KeysetQueryBuilder.cs:211-257) is the inverse: unwrapNullable<T>(:215), short-circuit forstring(:216-220), parseDateTimeandDateTimeOffsetwithDateTimeStyles.RoundtripKind(:222-242) so the "O" textToInvariantStringwrote comes back with its kind and offset intact (a UTC stamp stays UTC instead of being converted to the host's local time), otherwise useTypeDescriptor.GetConverterandConvertFromInvariantString(:244-251, returningfalseup front when the converter cannot read a string,:245-246), catching onlyFormatException,NotSupportedException, andArgumentExceptionand turning them intofalse(:253-256). A malformed cursor is a validation result, never an exception escaping the repository.Compare(left, right, greaterThan)(KeysetQueryBuilder.cs:310-351) is the provider-translatability layer, and the remarks at:300-309explain why it cannot just callExpression.GreaterThan: that factory only exists for types that have the operator, which excludesstring. So strings compare throughstring.Compare(string, string), which EF translates into a native>or<(:314-320). Expression trees define no relational operator on an enum either, so an enum (or nullable enum) key is converted to its underlying integral type (made nullable when the key is) and compared through a recursiveComparecall on the converted operands (:322-327), which matches the integral column an enum maps to by default. Types with a relational operator use it directly (:329-334); and anything else with anIComparable<T>implementation (aGuidkey, for instance) compares throughCompareTo(:336-350), whose translation is provider-specific. A type with none of these gets aNotSupportedExceptionnaming the type (:337-341), which is a loud failure at query-build time rather than a wrong result.SupportsRelationalOperator(KeysetQueryBuilder.cs:353-361) enumerates the primitive, decimal, date and time (DateTime,DateTimeOffset,DateOnly,TimeOnly), andTimeSpancases, and falls back to reflecting for a public staticop_GreaterThan; enums are not in the list, becauseComparehas already converted them before it gets here.StringCompareMethodandZeroConstant(:363-366) are resolved once as statics.
- Why it's built this way: keyset paging is declared as a repository-level capability, deliberately not part of the HTTP query contract of ADR-034, and ADR-055 records that split along with the cursor format. Building the predicate as an expression tree rather than as SQL text is what keeps the same code working on more than one provider (ADR-018); reusing
SpecificationEvaluator's ordering step rather than reimplementing the ordering call means the keyset ORDER BY and the specification ORDER BY are produced by the same code. - Where it's used: only by
EFReadRepository<TEntity, TIdentifierType>'sGetPageByCursorAsync, which callsTryResolveSortProperty(EFReadRepository.cs:651),ApplyOrdering(:667),ToInvariantStringtwice when encoding the next cursor (:682-683), and, through the privateTryBuildSeekPredicate,TryFromInvariantString(:704,:713) andBuildSeekPredicate(:718-719), passingnullsSortFirstAscendingfrom the engine behind the context. Covered byEFReadRepositoryKeysetPagingTests.csunderMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Repositories/Read/, and byKeysetQueryBuilderSqlTests.cs,KeysetQueryBuilderComparisonTests.cs,KeysetQueryBuilderCursorValueTests.cs,KeysetQueryBuilderEnumSortTests.csandKeysetQueryBuilderNullOrderingTests.csunderMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Repositories/Keyset/. - Caveats / not-in-source: the
NotSupportedExceptionfor an unorderable key type and the provider-specific translation ofCompareToare both real limits of the design, and neither is discoverable until a query is built for that key type.nullsSortFirstAscendingdefaults totrue(KeysetQueryBuilder.cs:123), so a caller that omits it gets SQL Server and SQLite null placement, which is the wrong side of the boundary for PostgreSQL; the one production caller always passes the engine's value (EFReadRepository.cs:732-733). No first-party call site in MMCA.ADC or MMCA.Store callsGetPageByCursorAsynctoday (the only references outside MMCA.Common are the test-support fakes inMMCA.ADC/Tests/Modules/Conference/MMCA.ADC.Conference.Application.Tests/Support/TestSupport.csand its Identity sibling), so which key and sort types have actually been exercised against a real engine is established by the test suite rather than by production usage.
EFReadRepositoryDecorator<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepositoryDecorator.cs:17· Level 6 · class (internal)
- What it is: a pass-through decorator over
IReadRepository<TEntity, TIdentifierType>that wraps every asynchronous operation in a MiniProfiler timing step, for per-query performance visibility in development (EFReadRepositoryDecorator.cs:10-17). - Depends on:
IReadRepository<TEntity, TIdentifierType>(both the interface it implements and the inner instance it holds,EFReadRepositoryDecorator.cs:17-23) andProfilingHelperfor the timing steps (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/ProfilingHelper.cs:9,:11-12,:26-30). - Concept introduced, the decorator as an opt-in cross-cutting wrapper.
[Rubric §2, Design Patterns]assesses whether the decorator pattern is used where behavior must compose without modifying the decorated type,[Rubric §13, Observability and Operability]assesses whether the system can be asked where its time goes, and[Rubric §1, SOLID]covers the open-closed consequence:EFReadRepository<TEntity, TIdentifierType>contains no profiling code and does not know profiling exists. Because both types implement the same interface, the decision to profile is a composition decision made once at construction time, not a branch inside every method. This is the same decorator idea the CQRS pipeline uses for logging, caching, and transactions, applied one layer lower. - Walkthrough
ClassNameis aconstset to the string"EFReadRepository", not to the decorator's own name (EFReadRepositoryDecorator.cs:22). That is deliberate: the profiler timeline should name the operation being measured, and the decorator is an implementation detail of measuring it.ProfilingHelper.BeginStepprefixes it with the assembly name to produce the labelMMCA.Common.Infrastructure.EFReadRepository: {method}(ProfilingHelper.cs:11-12)._inneris guarded at construction (EFReadRepositoryDecorator.cs:23).- Every asynchronous member is one expression-bodied forwarder of the same shape:
ProfilingHelper.ProfileAsync(ClassName, nameof(Member), () => _inner.Member(...)). The full set isGetAllAsync(:25-34),GetProjectedAsync(:36-43), bothFirstOrDefaultAsyncoverloads (:45-52,:54-58),CountByAsync(:60-66),SumByAsync(:68-75),FindIncludingDeletedAsync(:77-83),GetAllForLookupAsync(:85-91),GetByIdsAsync(:93-100), bothGetByIdAsyncoverloads (:102-104,:106-108), all threeCountAsyncoverloads (:110-112,:114-116,:118-122), bothExistsAsyncoverloads (:124-126,:128-130), bothListAsyncoverloads (:132-136,:138-143),AnyAsync(:145-149), andGetPageByCursorAsync(:151-156). Overloads share onenameof, so they appear under one label in the profile. - The four queryable properties are not profiled:
Table,TableNoTracking,TableNoTrackingSingleQuery, andTableNoTrackingSplitQueryare plain forwarders (EFReadRepositoryDecorator.cs:158-161), and so isQueryFor(specification)(:163-164), whose comment states the same reason: it composes a query without executing one, so there is nothing to time. That is correct rather than an omission: those members only build a queryable, and the time that matters is spent wherever the caller finally materializes it. - The class is
internaland, unlike its sibling, not sealed, becauseEFRepositoryDecorator<TEntity, TIdentifierType>derives from it.
- Why it's built this way: an explicit hand-written decorator over a generic interface with a stable member list keeps the profiling surface obvious and debuggable, at the cost of one forwarder per member. The wrapping is conditional at composition time, so a host with profiling off pays nothing at all, not even a delegate hop.
ProfilingHelper.BeginStepitself null-conditionals offMiniProfiler.Current, so even a wrapped call is a no-op when no profiler is running (ProfilingHelper.cs:11-12). - Where it's used: applied by
RepositoryFactory'sCreateReadOnlyonly whenUseMiniProfileris true on the application settings (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:58-63, with the doc stating the condition at:45-49). Extended byEFRepositoryDecorator<TEntity, TIdentifierType>. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/EFReadRepositoryDecoratorTests.csand.../EFReadRepositoryDecoratorAdditionalTests.cs.
EFRepositoryDecorator<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepositoryDecorator.cs:14· Level 7 · class (internal sealed)
- What it is: the read-write half of the profiling decorator. It extends
EFReadRepositoryDecorator<TEntity, TIdentifierType>and adds forwarders for the mutation members ofIRepository<TEntity, TIdentifierType>: add, row-version, concurrency touch, execute-delete, and execute-update (EFRepositoryDecorator.cs:14-54). - Depends on:
IRepository<TEntity, TIdentifierType>, its base classEFReadRepositoryDecorator<TEntity, TIdentifierType>,ProfilingHelper,IRowVersionedfor the child-entity concurrency overload (EFRepositoryDecorator.cs:35), andIUpdatePropertySetter<TEntity>in theExecuteUpdateAsyncsignature (:50). - Concept, decorating a derived contract by passing the same instance twice.
[Rubric §1, SOLID]. The declaration is the interesting line:EFRepositoryDecorator(IRepository<...> inner)deriving fromEFReadRepositoryDecorator<...>(inner)while implementingIRepository<...>(EFRepositoryDecorator.cs:14-18). The singleinnerargument is handed to the base constructor as anIReadRepositoryand stored again in this class's own_inneras anIRepository(:21). One object, two typed references: the inherited read members forward through the base's field, the write members through this one. That works precisely becauseIRepository<TEntity, TIdentifierType>extendsIReadRepository<TEntity, TIdentifierType>andIWriteRepository<TEntity, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:508), so the read decorator can be reused verbatim rather than re-forwarded. - Walkthrough
ClassNameis"EFRepository"here (EFRepositoryDecorator.cs:20), so writes appear under the read-write repository's label while inherited reads keep the read repository's label.- Every profiled write is asynchronous and follows the base's
ProfilingHelper.ProfileAsyncshape:AddAsync(:23-25),AddRangeAsync(:27-29),ExecuteDeleteAsync(:42-46), andExecuteUpdateAsync(:48-53). There is no synchronous profiled write, so this class never uses theBeginStephelper shape. - Both
SetOriginalRowVersionoverloads, the entity one and theIRowVersionedchild one, are unprofiled straight pass-throughs (EFRepositoryDecorator.cs:31-36). They only stamp an original value on a change-tracker entry, so there is no I/O to time. TouchConcurrencyToken(entity)(EFRepositoryDecorator.cs:39-40) is a third unprofiled pass-through, forwarding straight to_inner.TouchConcurrencyToken(entity)for the same reason: no I/O to time until the entity is actually saved.sealed, unlike its base: nothing derives from it.
- Why it's built this way: inheriting the read decorator rather than composing a second one avoids duplicating twenty-one forwarders, and keeps the two class-name labels distinct so a profile distinguishes a read issued through the write repository from one issued through a read-only repository.
- Where it's used: applied by
RepositoryFactory'sCreatewhenUseMiniProfileris true (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:34-39, documented at:21-25). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/EFRepositoryDecoratorTests.csand.../EFRepositoryDecoratorAdditionalTests.cs. - Caveats / not-in-source: there is no
SaveorSaveChangesAsyncforwarder here, and none is missing: flushing isIUnitOfWork's job, not the repository's, soIWriteRepository<TEntity, TIdentifierType>declares no save member at all (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:385-495). Nor is there anUpdateAsyncorUpdateRangeforwarder: the write contract declares no such member (its only update is the set-basedExecuteUpdateAsyncatIRepository.cs:491), because a tracked entity loaded through the repository is updated by mutating it and saving.
EFReadRepository<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:21· Level 9 · class (internal)
- What it is: the EF Core implementation of
IReadRepository<TEntity, TIdentifierType>, the read half of the repository contract: get by id, get many, projected reads, first-or-default, grouped counts and sums, soft-delete-aware finds, lookups, counts, existence checks, specification-driven reads, and keyset pages, with no mutation surface at all (EFReadRepository.cs:16-21). - Depends on: EF Core's
DbContextandDbSet<TEntity>, taken as its one primary-constructor parameter (EFReadRepository.cs:21-33);IReadRepository<TEntity, TIdentifierType>as the contract (declared atMMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:332);AuditableBaseEntity<TIdentifierType>as the entity constraint (:24);SpecificationEvaluator,KeysetQueryBuilder, andQueryTagsas its composition helpers;ApplicationDbContextfor the soft-delete filter name (:41) and for the engine behind the context, whoseDataSourceEngineCapabilitiesdrive the existence check and keyset null ordering (:511-512);EntityQueryPipeline.MaxUnboundedResultLimitfor the lookup row ceiling;LookupRow<TId, TName>as the intermediate projection shape for a non-string lookup name; andResult,Error,KeysetPageRequest,KeysetCollectionResult<T>,KeysetCursor, andBaseLookup<TIdentifierType>for the shapes it returns. - Concept introduced, naming the query filter you drop.
[Rubric §11, Security]assesses whether isolation boundaries hold under every code path, and[Rubric §8, Data Architecture]assesses whether the query-filter design is deliberate. EF 10 gives global query filters names, and the framework registers two on the model:SoftDeleteandTenant(ADR-073). EF's parameterlessIgnoreQueryFilters()drops all of them. That means a caller who only wanted to see soft-deleted rows would, with the parameterless call, also read across every tenant. So the repository declares a one-element array naming exactly the filter it is willing to drop (EFReadRepository.cs:35-41, resolvingApplicationDbContext.SoftDeleteFilterNamefromMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:712) and everyignoreQueryFilters: truepath passes it (:58,:87,:108,:203,:393,:469,:483,:580). This is the kind of detail worth copying wherever you add a filter-bypassing read. - Concept, tracked versus no-tracking as an explicit repository decision.
[Rubric §12, Performance and Scalability]. The four queryable properties atEFReadRepository.cs:524-533are the vocabulary:Table(tracked),TableNoTracking,TableNoTrackingSingleQuery, andTableNoTrackingSplitQuery. Read paths default to no-tracking to avoid change-tracker overhead, but two exceptions are load-bearing and both are commented in place, see the walkthrough below. - Walkthrough
MaxLookupSelectorCacheEntries = 512(EFReadRepository.cs:31) bounds the lookup-selector cache; past it a selector is built per request rather than cached, which the source calls correct and only slightly slower.- The protected get-only
Contextproperty is guarded at construction (EFReadRepository.cs:33), andEntitiesis avirtualproperty resolvingContext.Set<TEntity>()(:43); the engine-capability lookup reads the same property (:512). Every member goes through one of those two, which is what makes the class subclassable byEFRepository<TEntity, TIdentifierType>. - The private
BaseQuery(asTracking)helper (EFReadRepository.cs:548-549) picksTableorTableNoTrackingand tags the result throughQueryTagswith the ambient use-case tag. It backs every specification-less read (GetAllAsync,GetProjectedAsync,FirstOrDefaultAsync(where, ...),FindIncludingDeletedAsync,GetAllForLookupAsync,GetByIdsAsync,GetByIdAsync(id, includes, asTracking), and a specification-less keyset page);CountByAsyncandSumByAsynccall it withasTracking: falseexplicitly. Its doc (:535-545) records whyTableandTableNoTrackingstay untagged: they are the public, overridable extension point a consumer composes its own queries on, and the specification path is tagged insideSpecificationEvaluatorinstead, so no query is tagged twice. - Several members are plain
Task-returning methods, notasyncones: theyreturnthe EF call's task directly with noawaitand noConfigureAwait(false), because nothing runs after the query completes. That covers bothFirstOrDefaultAsyncoverloads (EFReadRepository.cs:96,:118), bothGetByIdAsyncoverloads (:402,:417), the threeCountAsyncoverloads (:433,:437,:447), bothExistsAsyncoverloads (:461,:475), andAnyAsync(specification)(:630). The argument guards (ArgumentNullException.ThrowIfNull) still run synchronously at call time, so a null argument throws at the call site instead of inside a faulted task. The members that post-process results stayasync(GetAllAsync,GetProjectedAsync,CountByAsync,SumByAsync,FindIncludingDeletedAsync,GetAllForLookupAsync, bothListAsync,GetPageByCursorAsync), as does the privateAnyAsynchelper (:498) whose ternary awaits either branch. GetAllAsync(EFReadRepository.cs:46-72) is the widest read: pick tracked or untracked (:55), optionally drop the named soft-delete filter (:57-58), apply includes (:60), then optionalwhere(:62-63), then optionalorderBy(:65-66), then materialize with or without aselect(:68-71). Every parameter is optional, which is what makes it the general-purpose read the older query paths call.GetProjectedAsync<TResult>(EFReadRepository.cs:75-93) is the projection-first read: no includes at all, because a projection selects its own columns, and theSelectis applied in the database rather than after materialization (:92).FirstOrDefaultAsync(where, includes, ...)(EFReadRepository.cs:96-115) is the predicate overload, and the comment at:113records the point: the predicate goes into EF'sFirstOrDefaultAsyncso the database issues aTOP 1, rather than materializing a set and narrowing it in memory.FirstOrDefaultAsync(specification)(EFReadRepository.cs:118-130) is the specification overload, and unlike the aggregate reads it applies the full shape, ordering included. The comment at:124-125is the reason: "first" is only meaningful against a defined order, and the specification is where that order is declared.CountByAsync<TKey>(EFReadRepository.cs:132-152) andSumByAsync<TKey>(:155-180) are the two grouped aggregates. Both run untracked, apply the optional predicate, group in the database, and project into the private recordsGroupedCount<TKey>(:147) andGroupedSum<TKey>(:175) before flattening to a dictionary (:151,:179). The comment at:170-172explains whySumByAsyncpasses the sum selector asGroupBy's element selector: it keeps the caller's expression tree intact all the way to the provider.FindIncludingDeletedAsync(EFReadRepository.cs:193-219) returns a named tuple of active and soft-deleted matches. The comment at:201-202is the design point: it drops the soft-delete filter and reads once, then partitions in memory (:210-218), because two separate queries would let a concurrent delete land between them and report the same row in neither half.GetAllForLookupAsync(EFReadRepository.cs:222-261) returns id and name pairs ordered by name, where "name" is a runtime property name.GetOrBuildLookupSelector(:320-341) returns an untypedLambdaExpressionrather than a fixedExpression<Func<TEntity, BaseLookup<TIdentifierType>>>, becauseBuildLookupSelector(:343-374) builds one of two projection shapes depending on the resolved property's CLR type: a string property projects straight toBaseLookup<TIdentifierType>with its name coalesced to empty (:365-373), while anything else projects toLookupRow<TId, TName>carrying the raw value (:349-363), because appendingToString()to the projection has no server-side translation for a value-object property and throwsInvalidOperationExceptionfor the whole query (the comment at:250-254).GetAllForLookupAsyncpattern-matches the returnedLambdaExpression(:240): the string leg runsSelect/OrderBy/Takeinline (:242-247); the non-string leg resolves the raw name's CLR type by reflection (:255) and dispatches, through the cachedExecuteRawLookupMethod(:267-268), to the public staticExecuteRawLookupAsync<TName>(:280-297), which runs the same ordered, capped projection againstLookupRow<TIdentifierType, TName>and formats each row's name in memory afterward (:292-296). Both legs keep.Take(EntityQueryPipeline.MaxUnboundedResultLimit)(:245,:288) BEFORE materialization, and the comment above the branch names why (:235-239, tagged SEC-Common-24): this path never entersEntityQueryPipeline, so the framework's row ceiling has to be applied here or a lookup stays the one unpaginated, uncapped read in the framework. Underneath,GetOrBuildLookupSelectorfirst resolves the property name to its CANONICAL spelling (:324-326, the SEC-Store-14 remark at:306-312) before keyingLookupSelectorCache(:313), checks the cache (:330-331), builds uncached rather than admitting a new entry onceMaxLookupSelectorCacheEntriesis reached (:335-336), and otherwise memoizes throughGetOrAdd(:338-340). Canonicalizing the name first is a fix, not a cosmetic change: reflection resolves a property name case-insensitively, so every case permutation of a real column used to mint its own never-evicted cache entry, 2^N spellings of an N-letter name, from an anonymous endpoint; resolving thePropertyInfofirst collapses them onto one entry.GetByIdsAsync(EFReadRepository.cs:377-399) materializes the id sequence once, short-circuits on an empty set with an empty result (:387-388), and translates to a singleContains(in other words a SQLIN) rather than N round trips (:398).GetByIdAsync(id)(EFReadRepository.cs:402-414) carries the single most important comment in the file (:408-412) and it encodes two separate bug fixes. First, it is a filtered query, notFindAsync:FindAsyncserves a tracked instance straight out of the identity map without evaluating the global soft-delete filter, so an entity soft-deleted earlier in the same scope came back as if it were live. Second, it queriesTable(tracked) on purpose:EFRepository<TEntity, TIdentifierType>inherits this member and the generic delete and update handlers load through it, mutate the instance, and save, so a no-tracking query would turn those writes into silent no-ops.GetByIdAsync(id, includes, asTracking)(EFReadRepository.cs:417-430) is the include-carrying overload and defaults to no-tracking, because a caller asking for includes is normally reading for display.- The three
CountAsyncoverloads (EFReadRepository.cs:433-456) cover no predicate, an expression predicate, and a specification. The specification overload composes throughSpecificationEvaluatorwithapplyShape: false(:454), so includes, ordering, and paging never reach a COUNT. - The two
ExistsAsyncoverloads (EFReadRepository.cs:461-486) both funnel into the privateAnyAsynchelper (:498-504), which is engine-aware. The remarks at:488-497are worth reading before you touch it: the non-relational engine (Cosmos DB) getsCountAsyncbecause its provider generates invalid SQL (an unresolvedrootidentifier) when translating a predicatedAnyAsyncinto a subquery; every relational engine getsAnyAsync, which short-circuits at the first match. The cost of the workaround is stated honestly in the same remark:CountAsyncreads every matching row, so on a wide predicate the Cosmos path is proportional to the number of matches. The switch is a capability, not a provider-name test:EngineCapabilities(:511-512,private protectedsoEFRepository<TEntity, TIdentifierType>can read the same capabilities for its row-version stamp) readsDataSourceEngineCapabilitiesoff theApplicationDbContext's engine, andTranslatesAny(:515) is itsIsRelationalflag. A plainDbContextthat is not a framework context (a directly constructed test double) yieldsnull, which the doc at:506-510reads as a relational engine that sorts nulls first, so bothTranslatesAnyandNullsSortFirstAscending(:521) fall back totrue. ApplyIncludes(EFReadRepository.cs:560-563) is aprotected staticforwarder toSpecificationEvaluator, including the collection-navigation split-query auto-switch. The doc at:551-559says why: the logic lives once so the string-include path and the specification path cannot drift apart.BaseQueryFor(EFReadRepository.cs:573-582) is the boundarySpecificationEvaluatorrefuses to cross. It readsAsTrackingandIgnoreQueryFiltersoff aQuerySpecification<TEntity, TIdentifierType>when the specification is one, and gives a plainISpecificationthe untracked, filtered default.QueryFor(specification)(EFReadRepository.cs:585-596) is the composable counterpart ofListAsync: it applies the specification's criteria and query tag throughSpecificationEvaluatorwithapplyShape: falseoverBaseQueryFor(:591), then the specification's includes on their own (:593-595), and returns theIQueryable<TEntity>without executing it. The comment at:589-590states the split: ordering andSkip/Takebelong to the caller composing on top. It is declared onIReadRepository<TEntity, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:363), andEntityQueryService<TEntity, TEntityDTO, TIdentifierType>is the caller that composes on it (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:735-736).- The two
ListAsyncoverloads (EFReadRepository.cs:599-627) apply the specification to that base. In the projecting overload the comment at:620-621records the ordering rule:Selectcomes last, so ordering and paging run over entity rows and only the resulting page is projected. AnyAsync(specification)(EFReadRepository.cs:630-641) uses criteria only, through the same engine-aware existence check the predicate overloads use (:636-640).GetPageByCursorAsync(EFReadRepository.cs:644-701) is the keyset page, and it is the one read that returns aResultrather than a bare value, because two of its failures are caller errors rather than exceptions. An unknown sort column returnsError.InvalidEntityFieldwith the column and type named (:651-660); a malformed cursor returns a validation error with codeError.InvalidCursor(:666-676). Between those it starts fromBaseQueryor applies the optional specification withapplyShape: false(:662-664), then the seek predicate (:678), and the(sortKey, Id)ordering (:681). TheTake(request.PageSize + 1)at:685is the next-page probe, and the comment at:683-684explains the choice: the extra row is never returned, it only says whether a next page exists, which is cheaper and more honest than a COUNT over the whole set. The probe row is trimmed (:687-689), and a next cursor is encoded from the last surviving row only when there is more (:691-698).TryBuildSeekPredicate(EFReadRepository.cs:708-736) is the private decode-and-build, an instance method because it reads the engine's null ordering: reject a cursor that failsKeysetCursor.TryDecode(:715-716), reject an id segment that does not parse toTIdentifierType(:718-722), reject a sort segment that does not parse to the sort property's type (:724-730), and otherwise hand the parsed values toKeysetQueryBuildertogether withnullsSortFirstAscending: NullsSortFirstAscending(:732-733). That flag is what makes a nullable sort key page correctly on PostgreSQL, which sorts nulls last ascending where SQL Server and SQLite sort them first.
- Why it's built this way:
internalrather than public, and every membervirtual, is what letsEFRepository<TEntity, TIdentifierType>extend it with writes while consumers hold only the interface. Concentrating the tracking and filter-scope decisions here and pushing pure composition intoSpecificationEvaluatorandKeysetQueryBuilderis what keeps this class about policy and those about mechanism. The contract and its evolution are recorded in ADR-055; the interface segregation intoIEntityReader<TEntity, TIdentifierType>andIEntityQuerier<TEntity, TIdentifierType>beneathIReadRepositoryis what makes a read-only consumer unable to write at all (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:21,:80,:332). - Where it's used: constructed by
RepositoryFactory'sCreateReadOnlythrough a cachedActivatorUtilitiesfactory taking theDbContext(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:55-56), optionally wrapped inEFReadRepositoryDecorator<TEntity, TIdentifierType>(:58-63). Application code reaches it throughIUnitOfWork'sGetReadRepository, implemented atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:68-81. Covered byEFReadRepositoryReadSurfaceTests.cs,EFReadRepositoryKeysetPagingTests.cs,EFReadRepositorySpecificationTests.cs,EFReadRepositoryGetByIdFilterTests.cs,EFReadRepositoryProjectedFilterTests.cs,EFReadRepositoryLookupProjectionTests.cs, andEFReadRepositoryLookupSecurityTests.csunderMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Repositories/Read/. - Caveats / not-in-source:
GetAllForLookupAsyncresolvesnamePropertyby reflection at runtime (EFReadRepository.cs:324-326), so an unknown name fails from the expression build rather than at compile time; the source contains no validation of that argument beyond whatExpression.Propertyitself enforces. It is capped byEntityQueryPipeline.MaxUnboundedResultLimiton both the string and the raw-value leg (:245,:288), so unlikeFindIncludingDeletedAsync, which still partitions in memory and materializes every matching row including the deleted ones with no upper bound on that set, a lookup can no longer read an unbounded table.
EFRepository<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:27· Level 10 · class (internal sealed)
- What it is: the read-write EF Core repository. It extends
EFReadRepository<TEntity, TIdentifierType>with add, concurrency-token, and set-based delete and update operations, implementingIRepository<TEntity, TIdentifierType>(EFRepository.cs:11-33). It stages changes and never saves: the class doc says so outright at:16. - Depends on: the base read repository, constructed with the same
DbContext(EFRepository.cs:28,:30) and reached through the base class's protectedContextproperty for everyEntryand model lookup (:54,:65,:75,:145); a requiredTimeProvider(:28) and one optional constructor dependency,ICurrentUserService(:29);UpdatePropertySetterBuilder<TEntity>for set-based updates (:109);AuditableAggregateRootEntity<TIdentifierType>as the entity constraint (:31); andAuditableBaseEntity<TIdentifierType>,IRowVersioned, andIAuditableEntityfor the concurrency and audit member names. - Concept introduced, the two write paths and why one of them must stamp its own audit fields.
[Rubric §8, Data Architecture]assesses whether audit metadata is reliably captured, and[Rubric §12, Performance & Scalability]assesses whether a cross-cutting policy holds on every path rather than the common one. The framework's normal write path is change-tracked: load, mutate, save, and the save interceptors stampLastModifiedOnandLastModifiedByand dispatch domain events. The second path is set-based:ExecuteUpdateandExecuteDeleteissue one SQL statement over matching rows without loading or tracking them, which is far cheaper on a wide update but bypasses the save pipeline entirely, interceptors included. Rather than pretend the two paths are the same, this class closes the gap explicitly for audit fields onExecuteUpdateAsync(EFRepository.cs:117-131). The class-level<remarks>(:20-25) states what the requiredTimeProviderand the optionalICurrentUserServiceare for: both serveExecuteUpdateAsync's own audit stamping since that path bypasses the save pipeline. The code goes one step further than those remarks: with no current user (no user service, or a background or system scope with no user id),LastModifiedByis stamped with the identifier type'sdefaultsentinel rather than left alone (:122-128), exactly as the save pipeline attributes a system save, because leaving the column untouched would keep crediting the change to the previous human editor. - Concept, the optional dependency as a testability affordance.
[Rubric §14, Testability]. OnlyICurrentUserServicedefaults tonull(EFRepository.cs:30);TimeProvideris a required constructor argument (:28), so a test must pass one explicitly (typicallyTimeProvider.Systemor a fake), while production construction throughActivatorUtilitiesfills both from the container. TakingTimeProviderat all, rather than callingDateTime.UtcNow, is what makes the timestamp deterministic under test, which is exactly whatEFRepositoryAuditStampTestsexercises. - Walkthrough
AddAsyncandAddRangeAsync(EFRepository.cs:36-47) are thin guarded forwarders toEntities.AddAsyncandAddRangeAsync.AddAsyncis the oneasyncmember, awaiting the EF call withConfigureAwait(false)(:38). Nothing is saved here; persistence happens at the unit of work's save.- There is no
UpdateAsyncorUpdateRangemember. A change-tracked update is not a repository call at all: the handler loads the aggregate tracked (the inheritedGetByIdAsync), mutates it through its own methods, and the change tracker turns that into the UPDATE at the unit of work's save. The only update the repository exposes is the set-basedExecuteUpdateAsyncbelow. - The two
SetOriginalRowVersionoverloads (EFRepository.cs:50-69) implement optimistic concurrency by writing the client's known row version into the tracked entry's original value, so EF's generated UPDATE carries it in the WHERE clause and a concurrent modification raises a concurrency exception instead of silently winning. Both null-guard their arguments and then assign unconditionally (:51-56,:62-67). The second overload takes anIRowVersionedchild entity and casts toobjectforEntry(:65), which is how a child of the aggregate gets the same protection without being an aggregate root itself. TouchConcurrencyToken(entity)(EFRepository.cs:72-90) forces a concurrency check on a root that a caller wants to protect even though nothing on it changed. It is a no-op unless the tracked entry's state is exactlyUnchanged(:80-83): a root the applier already modified emits its own UPDATE carrying the concurrency predicate already, and marking a property modified on aDeletedorDetachedentry would be wrong rather than merely redundant. When the entry is unchanged, it marks theLastModifiedOnaudit propertyIsModified = true(:88), which is what puts the row in the generated UPDATE at all; the audit interceptor then fills in the real value, so the write is a genuine edit record rather than a no-op touch, and EF appendsWHERE RowVersion = @originalfrom the concurrency token.AddRangeAsync(EFRepository.cs:43),ExecuteDeleteAsync(:92) andExecuteUpdateAsync(:101) are plainTask-returning methods that return the EF task directly, with noasync,awaitorConfigureAwait(false), since nothing follows the awaited call. Their argument guards and, forExecuteUpdateAsync, the whole audit and row-version stamping run synchronously before the task is returned.ExecuteDeleteAsync(EFRepository.cs:93-99) is the set-based delete:Entities.Where(where).ExecuteDeleteAsync(...), returning the affected row count (:97).ExecuteUpdateAsync(EFRepository.cs:102-134) is the flagship. It guards both arguments (:106-107), constructs anUpdatePropertySetterBuilder<TEntity>(:109), lets the caller describe the assignments against the persistence-agnostic interface (:110), and throwsArgumentExceptionwhen nothing was described (:111-112). Then it stamps:LastModifiedOnfromtimeProvider.GetUtcNow().UtcDateTimeunless the caller already set it (:116-120), andLastModifiedByunless the caller already set it (:125-128), withcurrentUserService?.UserId ?? default, so a scope with no current user records the default sentinel as the editor (the comment at:122-124). Both guards go throughbuilder.SetsProperty, so an explicit caller assignment always wins. It then calls the privateStampRowVersion(:130, defined at:141-149), and finally the recorded assignments are replayed into EF as a method group (:132).StampRowVersionexists because on an engine with no server-generated row version (PostgreSQL, SQLite) the token is written by the audit interceptor, whichExecuteUpdatealso bypasses: without a fresh value a client still holding the pre-update token would pass its If-Match check. So whenEngineCapabilities?.RowVersionisRowVersionStrategy.ClientStamped(:143, theprivate protectedcapability property inherited fromEFReadRepository<TEntity, TIdentifierType>), the caller did not setRowVersion(:144), and the EF model actually maps that property for the entity (:145), it assignsGuid.NewGuid().ToByteArray()(:147). SQL Server'srowversionmoves by itself, so nothing is stamped there.sealed, and the mutation members are non-virtual: this is the end of the inheritance chain.
- Why it's built this way: keeping the write members on a subclass of the read repository rather than on a parallel type means the read behavior a write handler relies on (the tracked
GetByIdAsync, most of all) is literally the same code a query handler runs. The contract is ADR-055, and the split between staging here and flushing inIUnitOfWorkis what makes one transaction span several repositories. - Where it's used: constructed by
RepositoryFactory'sCreatethrough the same cachedActivatorUtilitiesfactory (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:31-32), optionally wrapped inEFRepositoryDecorator<TEntity, TIdentifierType>(:34-39). Application code reaches it throughIUnitOfWork'sGetRepository(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:48). Covered byEFRepositoryAdditionalTests.cs,EFRepositoryAuditStampTests.cs,EFRepositoryConcurrencyTouchTests.cs, andEFRepositoryIntegrationTests.csunderMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Repositories/. - Caveats / not-in-source:
ExecuteUpdateAsyncandExecuteDeleteAsyncbypass the save pipeline, so beyond the two audit columns stamped here they raise no domain events and run no other interceptor, the tenant guard included. The source stamps the two audit columns, plus a freshRowVersionon client-stamped engines (:130,:141-149), and nothing else; whether a given set-based call site needed an event is a judgement the framework does not make for you. The class-level remarks match the body: without a user service (direct construction in tests) or without a current user (a background or system scope),LastModifiedByis stamped with the default sentinel, exactly as the save pipeline attributes a system save (EFRepository.cs:23-25), and the method stamps it unless the caller set it, withcurrentUserService?.UserId ?? default(:126-129). The class summary is current too: it states that tracked entities are updated by mutating them, so there is no per-entity update method (:14-15).
TenantDataSourceOverrideSettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Tenancy·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:152· Level 0 · class (sealed)
- What it is: one tenant's connection override for one physical data source, bound from
Tenancy:Tenants:{tenantId}:DataSources:{sourceName}. It is the entire configuration surface of database-per-tenant (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:152-171). - Depends on: nothing. It is the value type of
TenantEntrySettings.DataSources(TenancySettings.cs:143), validated byTenancySettingsValidatorand consumed byDbContextFactory. - Concept introduced, two isolation models behind one switch.
[Rubric §8, Data Architecture]assesses how tenant data is partitioned. Shared-schema isolation (a tenant column plus a global query filter andTenantSaveChangesInterceptor) needs no entry here at all: the sibling doc says declaring a tenant is only required for the database-per-tenant case, because shared-schema isolation comes from the filter and the interceptor rather than from configuration (TenancySettings.cs:123-128). Adding an entry upgrades exactly one source for exactly one tenant to its own database, and every other source stays shared.[Rubric §11, Security]: the strongest isolation available (a separate database) becomes a configuration decision per tenant per source rather than an architectural fork, which is what ADR-073 set out to make possible. The deliberate omission teaches as much as the members: there is no migrations-assembly override, because a tenant database has the same schema as the shared one (TenancySettings.cs:146-151). One schema, N connection strings. - Walkthrough
- Five nullable
{ get; init; }strings, one per engine plus the Cosmos database name:SQLServerConnectionString(TenancySettings.cs:155),PostgreSQLConnectionString(:144),SqliteConnectionString(:147),CosmosConnectionString(:150). CosmosDatabaseName(:153) is optional: when omitted the shared source's database name is kept, which is how one Cosmos account can serve per-tenant databases (:149-152).- The read path is a record
withclone, and it is the interesting part.DbContextFactory.ResolveTenantOverridebails out unless there is a resolved tenant, bound tenancy settings, an entry for that tenant, and an entry for that source name (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:173-179), picks the connection string for the source's engine throughTenancySettingsValidator.ConnectionStringFor(:154, resolver atTenancySettingsValidator.cs:150-151), and returns null when the tenant overrides this source on a different engine only (DbContextFactory.cs:182-186). Otherwise it clones the sharedPhysicalDataSourcewith the new connection string and, if supplied, the new Cosmos database name (:161-168). - The clone keeps the ORIGINAL
DataSourceKey, and the comment above it explains why (DbContextFactory.cs:165-170): EF's model cache is keyed on that key, so replacing only the connection string is what lets one compiled model serve every tenant's database.
- Five nullable
- Why it's built this way:
[Rubric §12, Performance & Scalability]is the reason for the key-preserving clone. A per-tenantDataSourceKeywould build and cache a separate EF model per tenant, which multiplies startup cost and memory by the tenant count for no schema difference. - Where it's used:
DbContextFactoryat context-creation time (DbContextFactory.cs:105-113), andTenancySettingsValidatorat startup, which rejects an entry that declares no connection string at all (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:104-114) and an entry whose key is not a real physical source name for the engine it declares (:93-104, with the round-trip test at:117-119). The second check exists because the alternative is a silent fall back to the shared database, which is precisely the failure database-per-tenant is bought to prevent. - Caveats / not-in-source: an override is keyed by physical source name (the name
IDataSourceResolverproduces), not the logical name a module uses (TenancySettings.cs:137-142). That distinction is invisible in a single-database host, where everything collapses ontoDefault.
TenantResolutionStrategy
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Tenancy·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:6· Level 0 · enum
- What it is: how the request pipeline looks for the tenant on an inbound request: from a signed claim or from a request header. Those are the only two members (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:6-22). - Depends on: nothing. Ordered into a list by
TenancySettings.ResolutionOrder(TenancySettings.cs:76), checked byTenancySettingsValidator, and switched on byTenantResolutionMiddleware. - Concept introduced, trusted versus asserted identity of a tenant.
[Rubric §11, Security]assesses whether an authorization-relevant value can be forged by the caller. The two members are not equivalent and the XML doc says so.Claimreads the tenant from the authenticated principal (TenancySettings.cs:8-13): the claim was signed by the token issuer, so a caller cannot pick its own tenant.Headerreads it from a request header (:15-21): fine for service-to-service calls behind a trusted gateway, and a public edge honoring it lets any caller name any tenant. The default order is the claim only (TenancySettings.cs:57-58): header resolution is a double opt-in, a host listingClaimthenHeaderinTenancy:ResolutionOrderAND settingTenancy:TrustTenantHeader(:67-73,:100-107), so the trustworthy source always wins when both are present and a public edge never honors the header by accident. - Walkthrough
Claim = 0(TenancySettings.cs:13), read viacontext.User?.FindFirst(settings.ClaimType)?.Value(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs:111); the claim type defaults totenant_id(TenancySettings.cs:86).Header = 1(:21), read viacontext.Request.Headers[settings.HeaderName].FirstOrDefault()onlywhen settings.TrustTenantHeader(TenantResolutionMiddleware.cs:112-113); the header defaults toX-Tenant-Id(TenancySettings.cs:93). Any other value falls to the_ => nullarm and is skipped (TenantResolutionMiddleware.cs:114).- The order is read through
EffectiveResolutionOrder, not the bound list: an emptyResolutionOrderfalls back to the framework default, the claim alone (TenancySettings.cs:79-80). That indirection exists because the configuration binder ADDS to a pre-populated collection rather than replacing it, so a non-empty default would leave a host that configured its own order also running the framework's entries (:36-41).
- Concept, an unknown strategy value cannot silently no-op.
[Rubric §15, Best Practices & Code Quality]: the configuration binder drops a list element it cannot convert instead of failing, so a name the enum does not define (a typo, or a stale"Host"entry) would vanish and leave the default order in force.AddMultiTenancychecks the raw configured values instead throughTenancySettingsValidator.HasUnknownConfiguredStrategyand fails the boot (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:363-372,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:58-63), andTenancySettingsValidatorrejects a numeric value outside the enum (which the binder does accept) andHeaderwithout the trust opt-in (TenancySettingsValidator.cs:71-93). That is the fail-fast configuration contract (ADR-070) applied to rules data annotations cannot express. - Why it's built this way: keeping the enum to the strategies that are implemented, and rejecting anything else at boot, means the configured order is always exactly the order the middleware runs.
- Where it's used:
TenantResolutionMiddleware(TenantResolutionMiddleware.cs:109-115),TenancySettings.EffectiveResolutionOrder(TenancySettings.cs:79-80), andTenancySettingsValidator(TenancySettingsValidator.cs:58-63,:73-92).
BatchedDelete
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Retention·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Retention/BatchedDelete.cs:15· Level 1 · class (internal static)
- What it is: the one delete loop every retention sweep in the framework goes through. It removes the rows a predicate selects a page at a time (at most
BatchSize = 1000per statement,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Retention/BatchedDelete.cs:18) and reports the total it removed (BatchedDelete.cs:8-15). - Depends on: EF Core's
DbContext,EF.Property<T>andExecuteDeleteAsync,System.Linq.Expressionsfor the predicate and ordering expressions, andIAuditableEntityas the type it refuses (BatchedDelete.cs:1-4,:86-90). - Concept introduced, bounded deletes for bookkeeping tables.
[Rubric §12, Performance & Scalability]assesses whether a background job stays cheap as data grows. The class doc names the failure it prevents: a first sweep over a long-neglected table would otherwise be one enormous delete, with one lock footprint, one transaction and one long statement (BatchedDelete.cs:9-10). Paging the delete turns that into many short statements.[Rubric §8, Data Architecture]assesses whether persistence choices hold across engines: the sweep reads a page of ids and then deletes by id rather than deleting from a limited query, because every relational engine the purges run on translates anINlist while a limitedDELETEis not universally supported (:11-13).[Rubric §11, Security]assesses whether erasure is controlled: hard deletes here are allowed only for rows that carry no soft-delete obligation, which is the line ADR-005 draws between soft delete and erasure. - Walkthrough
DeleteAsync<TEntity, TOrderKey>(context, predicate, orderBy, reportDeleted, cancellationToken, batchSize = BatchSize)(BatchedDelete.cs:39-60) is the entry point the sweeps call. It sums the per-batch counts and callsreportDeleted(total)in afinally(:56-59), so the count is reported exactly once even when a batch throws or the sweep is cancelled mid-batch; a failed sweep cannot lose the count of what it destroyed (:32-35).DeleteBatchesAsync(BatchedDelete.cs:78-93) is the guard plus the enumerator. It throwsInvalidOperationExceptionwhenTEntityis anIAuditableEntity(:86-90): those rows are deleted by settingIsDeleted, and erasing one here would drop it from audit, restore and erasure accounting (:66-70). The check runs eagerly, before the async iterator starts.RunBatchesAsync(BatchedDelete.cs:95-135) does the work. It reads the single primary-key property name from the model (:103); the key must be oneGuidcolumn, as it is on every framework bookkeeping table (:63-64). Each loop reads up tobatchSizeids withAsNoTracking, the predicate and the ordering (:112-118), stops when none are left (:120-123), deletes those ids withExecuteDeleteAsyncand yields the count (:125-128), and stops after a short page (:130-133).- Cancellation is observed between batches and throws
OperationCanceledExceptionrather than ending the loop (BatchedDelete.cs:110); thefinallyinDeleteAsynchas already reported the partial count by the time the exception reaches the caller (:22-25,:36). A sweep cut short by shutdown therefore never reads as a completed one: the scheduled job runner records the run as not succeeded and keeps it due instead of stamping it Succeeded and moving it to the next day (:107-109), and the next sweep carries on from what is left (:24-25).
- Why it's built this way: the sweeps differ only in table, predicate and ordering column, so one loop owns the paging, the count reporting, the cancellation contract and the soft-delete refusal, and none of them can get one of those wrong on its own. The ordering column should have an index to serve it (
BatchedDelete.cs:31).batchSizeis a parameter only so tests can pass a small one (:37). - Where it's used:
OutboxCleanupServicefor outbox and inbox rows (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Administration/OutboxCleanupService.cs:187,:207,:225),InternalCommandCleanupService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/InternalCommands/Administration/InternalCommandCleanupService.cs:123,:164),AuditTrailCleanupJob(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailCleanupJob.cs:119) andRefreshSessionCleanupService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionCleanupService.cs:141).SoftDeleteEnforcementTestsBaselists it as an allowed hard-delete site, with the reason that for each sweep erasing IS the retention policy (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Domain/SoftDeleteEnforcementTestsBase.cs:39-44). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Retention/BatchedDeleteTests.cs(the cancel-between-batches case, which expectsOperationCanceledExceptionand the partial count, at:69, and the soft-deletable refusal at:99) and by the shared engine scenarioMMCA.Common/Tests/Shared/Persistence/BatchedDeleteScenario.cs:17, which each engine tier runs against its real server to prove the translation.
ExplicitAssemblyProvider
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Design·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:268· Level 1 · class (private sealed nested)
- What it is: a four-line
IEntityConfigurationAssemblyProviderthat returns the exact list of assemblies it was constructed with, nested insideDesignTimeDbContextHelper(DesignTimeDbContextHelper.cs:268-271). - Depends on:
IEntityConfigurationAssemblyProviderandSystem.Reflection.Assembly. - Concept: this is the design-time counterpart of
DefaultEntityConfigurationAssemblyProvider, and the contrast is the whole point.[Rubric §14, Testability]assesses whether a component's inputs can be supplied directly rather than discovered ambiently, and[Rubric §1, SOLID]assesses whether the dependency inversion actually buys substitutability. Because the assembly list sits behind an interface rather than a hard-coded scan, "scan the AppDomain" and "here are exactly these three assemblies" are two implementations of one contract, and the rest of the model-building stack cannot tell them apart. That is what letsdotnet efbuild a real model in a process where a scan would find nothing. - Walkthrough: a primary constructor takes
IReadOnlyList<Assembly>andGetConfigurationAssemblies()returns it unchanged (DesignTimeDbContextHelper.cs:268-270). No caching, no filtering, no ordering: the caller already decided. - Why it's built this way:
private sealedand nested means it exists only for the helper's own call path and cannot become a public extension point by accident. It is constructed from the caller'sConfigurationAssemblieslist with a spread so later mutation of the options object cannot change the model (DesignTimeDbContextHelper.cs:147). - Where it's used: built once per design-time context and used three ways, registered as the DI-visible
IEntityConfigurationAssemblyProvider(DesignTimeDbContextHelper.cs:217), passed directly to the context constructor (:57,:78), and handed to theEntityDataSourceRegistrythat decides which entities belong to which physical source (:110).
TenantEntrySettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Tenancy·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:135· Level 1 · class (sealed)
- What it is: one declared tenant, bound from
Tenancy:Tenants:{tenantId}. It holds exactly one member: that tenant's per-data-source connection overrides (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:132-144). - Depends on:
TenantDataSourceOverrideSettings, the value type of its dictionary (TenancySettings.cs:143, declared at:138). Held byTenancySettings.Tenants(:115). - Concept introduced, declaring a tenant is only required for the database-per-tenant case. This is the single most important thing to read off this class, and it is stated in its own doc (
TenancySettings.cs:123-128). A shared-schema tenant needs NO entry here at all, because its isolation comes from the global query filter and theTenantSaveChangesInterceptor, whichAddInfrastructureregisters unconditionally with a comment saying why (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:69-72). Configuration is therefore only how a tenant is PROMOTED to its own database.[Rubric §8, Data Architecture]assesses how deliberately data is partitioned. The dictionary is keyed by PHYSICAL data source name (the nameIDataSourceResolverproduces, for exampleDefaultorConference), and the key choice is load-bearing enough thatTenancySettingsValidatorfails the boot on a key that does not round-trip. A tenant can override some sources and share others: a source with an entry is routed to the tenant's own database, a source without one stays shared (TenancySettings.cs:137-142). - Walkthrough
DataSources(TenancySettings.cs:143): a get-onlyDictionary<string, TenantDataSourceOverrideSettings>bound fromTenancy:Tenants:{tenantId}:DataSources:{sourceName}. Get-only is the correct shape for a bound dictionary, since the configuration binder populates an existing instance rather than assigning a new one.
- Why it's built this way: keeping the per-tenant overrides one level below the tenant, rather than flattening connection strings onto the tenant entry, is what lets a single tenant be physically separated on one source while remaining shared on the others, which is the mixed model ADR-073 records.
- Where it's used: read by
DbContextFactory.ResolveTenantOverride, which looks up the current tenant then the requested source and clones the sharedPhysicalDataSourcewith the tenant's connection string while keeping the ORIGINALDataSourceKey, so one compiled EF model serves every tenant's database (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:171-196). Also expanded byTenantDataSourceTargets.Expand, which turns the shared sources plus every (tenant, overridden source) pair into the list the outbox and cleanup background services sweep (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:69-79), and validated per entry byTenancySettingsValidator(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:99-134).
NullDomainEventDispatcher
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Design·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:273· Level 2 · class (private sealed nested)
- What it is: a no-op
IDomainEventDispatcherwhoseDispatchAsyncreturnsTask.CompletedTask, nested insideDesignTimeDbContextHelperand used only there (DesignTimeDbContextHelper.cs:273-277). - Depends on:
IDomainEventDispatcherandIDomainEvent. - Concept: the Null Object pattern.
[Rubric §2, Design Patterns]assesses whether a named pattern is used where it genuinely fits rather than decoratively. ADbContextin this framework is constructed with a live service provider and resolves interceptors from it, one of which (DomainEventSaveChangesInterceptor) needs a dispatcher. Design time has no message bus, no handlers and no host, and it never callsSaveChangesanyway, so the dependency has to exist but must never do anything. Supplying a harmless implementation is cheaper and safer than making the dependency optional in the production type, where "optional" would mean a nullable field that every runtime path has to defend against. - Walkthrough: the single member is an expression-bodied
DispatchAsync(IEnumerable<IDomainEvent>, CancellationToken)returningTask.CompletedTask(DesignTimeDbContextHelper.cs:275-276). It ignores both arguments, which is the whole contract. - Why it's built this way: it is
private sealedand nested so it can never be resolved by a production host by mistake. Registering it as the singletonIDomainEventDispatcher(DesignTimeDbContextHelper.cs:164) is what lets the design-time container build the same interceptor set the runtime builds, which is the property that keeps a scaffolded migration honest: the design-time pipeline differs from the runtime pipeline in nothing that touches the model. - Where it's used: registered once in
BuildDesignTimeServices(DesignTimeDbContextHelper.cs:164); nowhere else in the codebase.
TenancySettings
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Tenancy·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:47· Level 2 · class (sealed)
- What it is: the
Tenancysection, bound byAddMultiTenancy(configuration): whether tenant resolution runs, how the tenant is found on a request, whether a request without one is rejected, whether a caller-supplied header may name the tenant, which paths bypass resolution, and which tenants are declared for database-per-tenant routing (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:24-28). - Depends on:
TenantResolutionStrategy(the strategy enum at the top of the same file,:6-22) andTenantEntrySettings(the value type ofTenants,:126). No externals, and deliberately no relational data annotations: the checks that matter here are relational, so they live inTenancySettingsValidator. - Concept introduced, "empty means the default" for bound collections. This is a genuine configuration-binder trap and the class documents it explicitly (
TenancySettings.cs:38-45). The .NET configuration binder ADDS to a pre-populated collection rather than replacing it. IfResolutionOrdershipped pre-filled with[Claim], a host that also wantedHeaderwould append to it and a host that configured its own order would end up running the framework's entries as well. The resolution is a pair of properties: the bound list starts empty (:73,:114), and the framework reads a computedEffective*projection that substitutes a private static default when the bound list is empty (:76-77,:117-118).[Rubric §11, Security]assesses where trust boundaries are drawn. The two strategies are not equivalent and the enum says so:Claimis the trustworthy source because the claim was signed by the token issuer, so a caller cannot pick its own tenant (:8-13), whileHeaderis intended for service-to-service calls behind a trusted gateway, and a public edge that honors it lets any caller name any tenant (:15-21). The default order isClaimalone (:54-55), andHeadertakes two opt-ins: listing it inResolutionOrderand settingTrustTenantHeader, which defaults off and whose absence fails startup validation whenHeaderis listed (:100-107).RequireTenantdefaults totrue; when a host turns it off an unscoped request still runs but reads no tenant-owned rows, because the query filter fails closed, so it reaches only endpoints over global data (:92-98).[Rubric §15, Best Practices & Code Quality]assesses whether a new capability is additive for existing hosts.Enabledgates RESOLUTION, not isolation: the global query filter and theTenantSaveChangesInterceptorare always registered and are inert whenever no tenant is resolved (:31-33,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:72). A host that never enables tenancy keeps exactly the behavior it had before tenancy shipped, and a host that does enable it can never accidentally leave the write-side guard off. - Walkthrough
SectionName = "Tenancy"(TenancySettings.cs:50), the one public static field.DefaultResolutionOrder(:54-55): private static[Claim], the signed claim only.DefaultExcludedPathPrefixes(:58-59): private static["/health", "/alive", "/.well-known"], the probe and discovery endpoints that must answer before any tenant exists.Enabled(:65): defaultfalse.ResolutionOrder(:73) get-only list plusEffectiveResolutionOrder(:76-77), the empty-means-default projection.ClaimType(:83), default"tenant_id", andHeaderName(:90), default"X-Tenant-Id", the two per-strategy lookup keys.HeaderNameis only honored whenHeaderis in the order andTrustTenantHeaderis set (:85-89).RequireTenant(:98): defaulttrue.TrustTenantHeader(:107): defaultfalse. Set it only where every request reaching the host has passed a gateway or a server-side client that sets the header itself (:100-106).ExcludedPathPrefixes(:114) plusEffectiveExcludedPathPrefixes(:117-118), the same projection shape.Tenants(:126): a get-onlyDictionary<string, TenantEntrySettings>bound fromTenancy:Tenants:{tenantId}, needed only for database-per-tenant.
- Why it's built this way: shared-schema isolation plus optional database-per-tenant promotion is the model ADR-073 records, and this class is its whole operator-facing surface. Defaulting
Enabledto false while keeping the filter and interceptor always-on is what makes the feature safe to ship into an existing host, and keeping every relational check in a separateIValidateOptions<T>(rather than in attributes) is what lets the validator reach the resolved data sources. - Where it's used: bound with
ValidateOnStartand a raw-value check for unknown strategy names inAddMultiTenancy, alongside theTryAddEnumerableregistration ofTenancySettingsValidator(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:359-379). Read at request time byTenantResolutionMiddleware, which short-circuits when disabled or on an excluded path (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs:63), walksEffectiveResolutionOrderreading the claim, or the header only whenTrustTenantHeaderis set (:107-118), lets the request through unscoped whenRequireTenantis off (:75-81), and otherwise answers400 Bad Request(:83). Read at persistence time byDbContextFactoryfor per-tenant connection routing (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:48,:144-168), and by the background services throughTenantDataSourceTargets.Expandso they sweep every tenant database too (OutboxProcessor.cs:72,OutboxCleanupService.cs:252,OutboxAdministration.cs:57,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:52-82). Startup database initialization uses the same expansion to create each tenant's database (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:205,:138), and the design-time helper supplies a default instance sodotnet efneeds no tenancy configuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:174). The startup configuration summary also reports it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/StartupConfigurationSummaryService.cs). All of the runtime consumers take the options as NULLABLE, so a host that never calledAddMultiTenancyresolvesnulland behaves exactly as before.
DesignTimeDbContextOptions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Design·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextOptions.cs:11· Level 9 · class (public sealed)
- What it is: the configuration carrier a migrations project fills in so
DesignTimeDbContextHelpercan build a context fordotnet efwithout the application's DI container. It holds the connection settings, the named data sources, the explicit list of entity-configuration assemblies, the strongly typed identifier assemblies, nine flags that decide which framework-owned tables belong to the scaffolded model, and the host's own model contributors (DesignTimeDbContextOptions.cs:11-279). - Depends on:
ConnectionStringSettingsandDataSourceEntrySettingsfromMMCA.Common.Infrastructure.Settings,IModelContributor(the element type ofModelContributors,:264), plusSystem.Reflection.Assembly. - Concept introduced, the design-time model has to be assembled by hand.
[Rubric §17, DevOps and Deployment]assesses whether the build and release machinery is deliberate rather than incidental, and[Rubric §33, Developer Experience]assesses how much ceremony a routine task costs. At run time the framework discovers entity configurations by scanning loaded assemblies, and it reads flags such asScheduler:Enabledout of the host's configuration.dotnet efhas neither: it loads the migrations project, callsIDesignTimeDbContextFactory<T>.CreateDbContext, and there is no host, noIConfiguration, and no AppDomain full of module assemblies to scan. Every input the model needs must therefore be stated explicitly, and this class is the shape of that statement. The doc comment says exactly that for the assemblies (DesignTimeDbContextOptions.cs:159-162): they must be listed explicitly, because the runtime scan sees nothing at design time. - Walkthrough
DataSourceName(DesignTimeDbContextOptions.cs:18) names the logical source to build for. When it is leftnullthe helper parses--datasourcefrom the design-time arguments and finally falls back toDefault(:13-17).ConnectionStrings(DesignTimeDbContextOptions.cs:24) is the top-level (Default) settings object, andDataSources(:27) is the dictionary mirroring theDataSourcesconfiguration section. Between them they reproduce, in code, exactly what a host'sappsettings.jsonwould supply.EnableScheduler(DesignTimeDbContextOptions.cs:41) puts theScheduledJobstable in the design-time model. It defaults tofalsesodotnet efkeeps producing the migrations it produced before the scheduler shipped (:29-34), and its remarks pin the scope: set it in the migrations project of theDefaultdata source of a host that callsAddScheduledJobs, and only there, because a second project enabling it would create a second copy of a host-scoped table (:35-40).EnableAuditTrail(DesignTimeDbContextOptions.cs:55) does the same forAuditTrailEntries, with the opposite scope rule: set it in every data source whose entities are audited, because a trail row is written to the database holding the entity that changed (:49-54).EnableRefreshSessions(DesignTimeDbContextOptions.cs:73) does the same forRefreshSessions, back to single-database scope: sessions are one module's data (:63-72). Its remarks name the one twist that separates it from the other two, and it is a real trap: there is no data-source setting to pass alongside the flag, because the helper registers the source the context actually resolved to, which is not always the logical name asked for.EnableStoredPermissionGrants(DesignTimeDbContextOptions.cs:87) puts thePermissionGrantstable (ADR-116) in the design-time model, with the same single-database scope asEnableRefreshSessions: set it in the migrations project of the databaseAddStoredPermissionGrantstargets, normally Identity (:79-81). Its remarks describe the same two-part gate the helper wires: the framework's model contributor is registered behind the flag, andAuthentication:PermissionGrants:DataSourceNameis pointed at the source this context resolved to, so the flag opens the gate for exactly the context--datasourceselected (:81-85).EnableViewAsGrants(DesignTimeDbContextOptions.cs:101) maps theViewAsGrantstable (ADR-137), mirroringViewAs:EnabledANDViewAs:HostsGrantStore(:89-93). Set it in the Identity database's migrations project only: in a multi-service host the other services run withViewAs:HostsGrantStorefalse and map no grant table (:94-100).EnableFeatureFlagOverrides(DesignTimeDbContextOptions.cs:115) maps theFeatureFlagOverridestable (ADR-031), and is the one per-service flag of the newer set: set it in the migrations project of each database whose service callsAddReloadableFeatureFlags, and the helper pointsFeatureFlags:DataSourceNameat the source this context resolved to (:103-114).EnablePasskeys(DesignTimeDbContextOptions.cs:129,PasskeyCredentials, ADR-139) andEnableMachineClients(:143,MachineClients, ADR-140) mirrorPasskeys:EnabledandMachineClients:Enabledand belong in the Identity database's migrations project only; the helper pointsPasskeys:DataSourceNameandMachineClients:DataSourceNameat the resolved source (:122-128,:136-142).EnableWebhooks(DesignTimeDbContextOptions.cs:157) mapsWebhookSubscriptions(ADR-142), mirroringWebhooks:Enabled; set it in the migrations project of the databaseWebhooks:DataSourceNamenames, and only there (:150-156).ConfigurationAssemblies(DesignTimeDbContextOptions.cs:163) is the explicit assembly list, andAddConfigurationAssembly(:168-177) is the chaining adder: null-guard (:170), add only when not already present (:171-174), returnthis(:176).UseSqlServerServiceDatabase(dataSourceName, connectionStringVariable, localDatabaseName, migrationsAssembly)(DesignTimeDbContextOptions.cs:201-224) is the one-call setup for a service's own SQL Server database (ADR-006). It guards all four arguments (:207-210), setsDataSourceName(:215), and declares the ONE namedDataSourcesentry with the connection string read from the environment variable, falling back to a trusted local connection tolocalDatabaseNameonly when the variable is unset, plus the migrations assembly name (:216-221). The remarks explain why one entry is enough: with no top-level connection string,DataSourceResolverpromotes the single named source toDefaultexactly as the running service host does, so the host-scoped tables gated onDefaultstay in the scaffolded model; a variable set to an empty string is used as-is (:187-195).StronglyTypedIdAssemblies(DesignTimeDbContextOptions.cs:236) and its chaining, de-duplicating adderAddStronglyTypedIdAssembly(:241-250) mirror the host'sAddStronglyTypedIds(assembly)calls (ADR-115). Empty by default, which registers no identifier registry; without the right assembly listed the design-time model has no value converter for a wrapped key, and building the model fails naming the property (:226-235).ModelContributors(DesignTimeDbContextOptions.cs:264) and its chaining, de-duplicating adderAddModelContributor(:269-278: null-guard, add only when the same instance is not already present, returnthis) carry the host's own model contributors (ADR-148), applied after the framework's, mirroring the contributors the host registers at runtime. Empty by default, which leaves the model exactly as before. The remarks say to construct each over the same settings the runtime host binds, with its data source name set to the source this migrations project scaffolds, and that each contributor still decides through its ownAppliesTo; a contributor the host registers but this list omits makes the scaffolded migrations and the running model disagree (:252-263).- Each of the nine flags defaults to
falseand carries the same warning in its remarks: the flag must match the host's configuration (or, for the per-service flags, the service's runtime model), or the scaffolded migrations and the running model disagree, which is whatdotnet ef migrations has-pending-model-changesreports (DesignTimeDbContextOptions.cs:70-71).
- Why it's built this way: database-per-service (ADR-006) means one migrations project per database, so the design-time entry point has to be told which database it is scaffolding rather than inferring it, and
UseSqlServerServiceDatabasemakes that statement one call. Making the framework-table flags default tofalseis the conservative choice: a consumer that never adopted the scheduler, the audit trail, multi-device sessions (ADR-097), stored permission grants (ADR-116), view-as, feature-flag overrides, passkeys, machine clients or webhooks scaffolds exactly what it scaffolded before, and adopting a feature is an explicit one-line opt-in in the right migrations project.ModelContributorsextends the same rule to the host's own optional tables: the design-time model applies the contributors the runtime registers, nothing more. - Where it's used: constructed and handed to the caller's callback inside
DesignTimeDbContextHelper(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:140-141). Every consumer's migrations projects configure it. In MMCA.ADC all four callUseSqlServerServiceDatabase, and Identity, Conference and Engagement enable the audit trail and the scheduler (Notification enables none of the flags,MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Notification/DesignTimeSQLServerDbContextFactory.cs:23); the Identity project also enables refresh sessions, stored permission grants, view-as grants, passkeys and machine clients (MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Identity/DesignTimeSQLServerDbContextFactory.cs:20,:36-57), and Conference and Engagement enable feature-flag overrides (MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Conference/DesignTimeSQLServerDbContextFactory.cs:33,MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Engagement/DesignTimeSQLServerDbContextFactory.cs:35). MMCA.Store's three projects follow the same shape, with refresh sessions and stored permission grants on Identity (MMCA.Store/Source/Hosting/MMCA.Store.Migrations.SqlServer.Identity/DesignTimeSQLServerDbContextFactory.cs:21,:38-46). MMCA.Helpdesk enables the audit trail, the scheduler and webhooks (MMCA.Helpdesk/Source/Hosting/MMCA.Helpdesk.Migrations.SqlServer.Tickets/DesignTimeSQLServerDbContextFactory.cs:44-46). The framework's own registration calls for feature flags, machine clients, passkeys and webhooks also mention it (DependencyInjection.FeatureFlags.cs,DependencyInjection.MachineClients.cs,PasskeysServiceCollectionExtensions.cs,WebhookServiceCollectionExtensions.cs). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/DesignTimeDbContextOptionsTests.cs.
TenancySettingsValidator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Tenancy·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:25· Level 10 · class (sealed, internal)
- What it is: the startup validator for
TenancySettings. It rejects a resolution order naming a strategy the enum does not define or namingHeaderwithout theTrustTenantHeaderopt-in, carries the raw-configuration checkAddMultiTenancyuses for unknown strategy names, and rejects a per-tenant data-source override that declares no connection string or names a source that does not exist (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettingsValidator.cs:10-25). - Depends on:
IDataSourceResolveras an OPTIONAL primary-constructor parameter (TenancySettingsValidator.cs:25), plusDataSourceandDataSourceKey(:4-5,:29-30,:131), the engine registryDataSourceEnginesand itsIDataSourceEngineentries (:6,:30,:151),TenantResolutionStrategy(:62,:75), and the two settings shapesTenancySettingsandTenantDataSourceOverrideSettings. Externals:Microsoft.Extensions.OptionsforIValidateOptions<T>andValidateOptionsResult(:3),Microsoft.Extensions.Configurationfor the rawIConfigurationcheck (:2,:58), andSystem.Globalizationfor theCultureInfo.InvariantCulturemessage formatting (:1,:87). - Concept introduced,
IValidateOptions<T>when validation needs other services. Data annotations andIValidatableObjectare the right tools when a rule only involves the settings object itself. This class is the other half of the options-validation story:IValidateOptions<T>is a DI-resolved service, so it can inject collaborators. Here that collaborator is the data-source resolver, which is the only thing that knows whetherConferenceis a real physical source in this host. Registration isTryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<TenancySettings>, TenancySettingsValidator>())(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:375-376), withTryAddEnumerablebecause two modules callingAddMultiTenancymust not run the same validation twice (DependencyInjection.cs:374). The same shape is used byConnectionStringSettingsValidator; these two are the framework's only customIValidateOptions<T>implementations.[Rubric §11, Security]assesses whether misconfiguration can degrade silently. The class doc states the rationale outright: every failure here would otherwise surface as silent cross-tenant behavior at run time, which is exactly the class of bug tenancy exists to prevent, so it is worth a failed boot (TenancySettingsValidator.cs:10-15). The concrete danger is the override key: an unknown logical name resolves toDefault, so a mistyped source name would quietly leave that tenant on the shared database instead of its own (:140-144). The header rule is the other trust check: listingHeaderwithoutTrustTenantHeaderwould let any caller pick any tenant, so it fails the boot with a message telling the operator when the opt-in is safe and what to do otherwise (:75-83).[Rubric §15, Best Practices & Code Quality]assesses the quality of failure messages. Each message names the exact configuration path that is wrong and tells the operator what to do: the missing-connection-string message lists the four acceptable properties and notes that removing the entry keeps the source shared (:106-112); the unknown-source message explains that override keys are physical names (:123-131); the unknown-strategy message names the two supported values (:85-91). - Walkthrough
Engines(:29-30): private static, built fromDataSourceEngines.Allordered by each engine'sSubstitutionPriorityand projected to itsEnginevalue. With the shipped priorities (SQL Server0, PostgreSQL1, Sqlite2, Cosmos3:MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:29,PostgreSQLDataSourceEngine.cs:27,SqliteDataSourceEngine.cs:26,CosmosDataSourceEngine.cs:27) that yields[SQLServer, PostgreSQL, Sqlite, CosmosDB], the engines an override can carry a connection string for, in substitution-priority order (:28). The list is not hand-written, so a newly registered engine is validated without touching this class.Validate(string? name, TenancySettings options)(:33-49): null-guards the options, collects failures into a list, runs the resolution-order check once and the tenant check per declared tenant, then returnsValidateOptionsResult.SuccessorFail(failures). Note that it accumulates ALL failures rather than returning on the first, so one boot attempt reports the whole set.HasUnknownConfiguredStrategy(IConfiguration tenancySection)(:58-63):internal static, reads the rawResolutionOrderchildren and reports whether any value failsEnum.TryParseplusEnum.IsDefined. It works on the raw values because the configuration binder drops a list element it cannot convert instead of failing (:51-57);AddMultiTenancywires it as an optionsValidatepredicate (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:366-372).ValidateResolutionOrder(:71-93): walksEffectiveResolutionOrder(so the framework default is validated too, not just an explicitly configured order). It fails onHeaderwhenTrustTenantHeaderis false (:75-83), and on any valueEnum.IsDefinedrejects (:85-91), which covers a numeric configuration value that binds to an arbitrary integer (:65-70).ValidateTenant(:99-134): for each(sourceName, override)pair, computes which engines the override actually declares a connection string for. Zero engines is a failure and the loop moves on (:104-113). Ifresolveris null the source-existence check is skipped entirely (:116-119), which is what makes the validator usable in a container that never registered persistence (:16-20). Otherwise every declared engine whose source name is unknown produces a failure (:121-132).DeclaredEngines(:137-138): a collection expression overEnginesfiltered byConnectionStringForbeing non-blank.IsKnownPhysicalSource(:145-147): the round-trip test.Defaultalways passes; otherwise the name must surviveresolver.ResolveLogical(engine, sourceName).Nameunchanged, because an unknown logical name collapses ontoDefaultand therefore comes back different.ConnectionStringFor(DataSource, TenantDataSourceOverrideSettings)(:150-151):internal static, a one-line delegation toDataSourceEngines.For(engine).GetConnectionString(over), so each engine answers for its own override property (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/IDataSourceEngine.cs:59).ForthrowsInvalidOperationExceptionfor an unregistered engine rather than returning null (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/DataSourceEngines.cs:40-43). It isinternalrather than private because it is reused outside validation, which is the detail worth noting next.
- Why it's built this way: the engine-to-property mapping is needed in three places (validation, target expansion, and connection routing). The mapping itself now lives on each engine (
GetConnectionString(TenantDataSourceOverrideSettings),IDataSourceEngine.cs:59), and this validator'sConnectionStringForis the single entry point the runtime paths call back into rather than resolving the engine themselves (ADR-073). DerivingEnginesfrom the registry follows the same rule:DataSourceEnginesdocuments that a fifth engine is one new class plus one registry line (DataSourceEngines.cs:14-17), and this validator picks it up with no edit. Making the resolver optional rather than required is what keeps the validator constructible in a host that binds tenancy without registeringAddInfrastructure, at the cost of skipping the source-existence check there; the strategy and connection-string checks still run. - Where it's used: registered by
AddMultiTenancyalongsideValidateOnStarton the options (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:359-379). ItsConnectionStringForhelper is called at run time byTenantDataSourceTargets.Expandwhen deciding whether a (tenant, source) pair is really overridden (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:74) and byDbContextFactory.ResolveTenantOverridewhen cloning the physical source for a tenant (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:181). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Tenancy/AddMultiTenancyTests.cs, which asserts the single-registration shape (:97-98) and drives the validator both without a resolver (:168) and with one (:206). - Caveats / not-in-source: the type is
internal, so it is not part of the framework's public API and a consumer cannot subclass or replace it; a host needing extra tenancy rules registers its own additionalIValidateOptions<TenancySettings>.
DesignTimeDbContextHelper
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.DbContexts.Design·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:55· Level 11 · class (public static)
- What it is: the whole design-time story in one static class. It builds a real
SQLServerDbContext,PostgreSQLDbContextorSqliteDbContextfordotnet efcommands without the application's host or DI container, so a consumer's migrations project is a factory class of a few lines (DesignTimeDbContextHelper.cs:31-54, with the worked example in the doc comment at:24-34;CreatePostgreSQLandCreateSqliteare its symmetric entry points,:37-42). - Depends on:
DesignTimeDbContextOptions(the caller's input),DataSourceResolverandEntityDataSourceRegistry(routing),ExplicitAssemblyProviderandNullDomainEventDispatcher(its two nested stand-ins), the four interceptors (AuditSaveChangesInterceptor,DomainEventSaveChangesInterceptor,TenantSaveChangesInterceptor,AuditTrailSaveChangesInterceptor),IModelContributorand the nine framework contributors registered only behind their flags (ScheduledJobModelContributor,AuditTrailModelContributor,RefreshSessionModelContributor,PermissionGrantModelContributor,ViewAsGrantModelContributor,FeatureFlagOverrideModelContributor,PasskeyCredentialModelContributor,MachineClientModelContributor,WebhookSubscriptionModelContributor),OutboxSignal,StronglyTypedIdRegistry(registered only when identifier assemblies are listed), and the settings typesTenancySettings,SchedulerSettings,AuditTrailSettings,RefreshSessionSettings,PermissionGrantSettings,ViewAsSettings,FeatureFlagOverrideSettings,PasskeySettings,MachineClientSettingsandWebhookSettings. Externally:Microsoft.Extensions.DependencyInjection,Microsoft.Extensions.Options, and the null-logger family fromMicrosoft.Extensions.Logging.Abstractions. - Concept introduced, the design-time container.
[Rubric §17, DevOps and Deployment]assesses whether migrations are a repeatable, per-database operation rather than a manual one, and[Rubric §33, Developer Experience]assesses how much a routine task costs the next engineer.dotnet efruns outside the application: it loads an assembly, finds anIDesignTimeDbContextFactory<T>, and asks for a context. ADbContextin this framework is not newable in isolation, because it resolves interceptors, a data-source resolver and an entity registry from a service provider. This helper builds the smallest provider that satisfies all of that, and the design principle running through every line ofBuildDesignTimeServicesis fidelity: register the same services the runtime registers, so the modeldotnet efsees is the model the application will run. The save pipeline is registered unconditionally (the tenant interceptor and options at:168-174, the audit-trail interceptor and settings at:175-180). The optional tables follow the model-contributor pattern of ADR-148: eachEnable*flag adds the SAME contributor the feature'sAddXcall registers at runtime, over settings that say "on, here", and a flag left off adds nothing, which is exactly a host that never opted in (:182-190). The contributor and the identifier registry are the switch, so their presence is what changes the model. - Walkthrough
CreateSqlServer(args, configure)(DesignTimeDbContextHelper.cs:64-73),CreatePostgreSQL(args, configure)(:86-95) andCreateSqlite(args, configure)(:107-116) are the three entry points. Each calls the shared builder for its engine and then constructs the context with an emptyDbContextOptions, the built provider, the assembly provider and the resolved physical source.BuildDesignTimeServices(DesignTimeDbContextHelper.cs:134-231) is the substance. Its doc comment states why it is shared: all three engines scaffold against exactly the same interceptor and options pipeline, because a difference between them would surface as a migration that differs by engine for reasons that have nothing to do with the engine (:118-122). It isinternalrather than private so the model snapshot tests can build each engine's context over exactly this wiring with EF's service-provider caching off, since the process-wide model cache does not key on configuration assemblies (:128-132). It returns the assembly provider typed asIEntityConfigurationAssemblyProvider(:134).- Name resolution is a three-step fallback (
DesignTimeDbContextHelper.cs:143-145): the explicitDataSourceName, then--datasourceparsed from the arguments, thenDataSourceKey.DefaultName. - The routing stack is built by hand: an
ExplicitAssemblyProviderover a copy of the caller's assembly list (DesignTimeDbContextHelper.cs:147), aDataSourceResolverover the caller's connection settings with a null logger (:148-151), and anEntityDataSourceRegistryover the two (:152). - The physical source is resolved before the registrations (
DesignTimeDbContextHelper.cs:158), and the comment at:154-157explains why the ordering matters: the model contributors gate on the PHYSICAL source name, which is not always the logical one asked for. A logical name whose connection matches the top-level one collapses ontoDefault, and names sharing a connection collapse onto the alphabetically-first of them. - The container (
DesignTimeDbContextHelper.cs:160-219) registersTimeProvider.System, aNullLoggerFactoryand open-genericNullLogger<>(:161-163), theNullDomainEventDispatcher(:164), anOutboxSignal(:165), the audit and domain-event interceptors (:166-167), the tenant interceptor with a default (disabled)TenancySettings(:173-174), and theAuditTrailSettings(enabled fromEnableAuditTrail) plus the interceptor that writes the trail (:178-180). - The model contributors are the part a migrations author actually tunes.
sourceis the resolvedphysical.Key.Name(DesignTimeDbContextHelper.cs:191), and nineAddContributorWhencalls each add one framework contributor when its flag is set, over settings stampedEnabled = trueand, for the source-scoped ones,DataSourceName = source: scheduler and audit trail (:192-195), refresh sessions, stored permission grants and view-as grants (:196-201), feature-flag overrides (:202-203), passkeys, machine clients and webhooks (:204-209). Each contributor still decides through its ownAppliesTo, so the job table still lands onDefaultonly, and stamping the physical rather than the logical name is what stops a contributor from declining on a collapsed source (:182-190). Then the host's ownModelContributorsare registered after the framework's (:211-215). AddContributorWhen(DesignTimeDbContextHelper.cs:237-243) is the private helper: it calls the factory and registers the result only when the flag is on.- The assembly provider, resolver and registry are registered under their interfaces (
DesignTimeDbContextHelper.cs:217-219). Then, only when the migrations project listed identifier assemblies, aStronglyTypedIdRegistryover them is registered so the context can give each wrapped key its value converter, asAddStronglyTypedIdsdoes at run time (ADR-115,:221-228); a model without wrappers is built exactly as before. The triple is returned (:230). ParseDataSourceName(DesignTimeDbContextHelper.cs:248-266) isinternalso it can be tested directly. It accepts both--datasource Nameand--datasource=Name, case-insensitively (:252,:259), and throwsInvalidOperationExceptionwith a usage hint when the flag is present with no value (:254-256). A missing flag returnsnull(:265), which is the fallback path, not an error.
- Why it's built this way: database-per-service (ADR-006) means one migrations project per database, and each of them needs a context whose model contains only that source's entities. Centralizing the plumbing here keeps each of those projects declarative, and centralizing it also means the fidelity rules (register the same pipeline, add the same contributors the runtime adds, key every source-scoped contributor on the resolved physical name) are stated once instead of once per consumer. Supporting all three engines through one private builder is the polyglot posture of ADR-018 and ADR-113.
- Where it's used: every consumer's design-time factories. MMCA.ADC has four (
MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Identity/DesignTimeSQLServerDbContextFactory.cs:14, Conference at:14, Engagement at:16, Notification at:17), MMCA.Store has three (MMCA.Store/Source/Hosting/MMCA.Store.Migrations.SqlServer.Identity/DesignTimeSQLServerDbContextFactory.cs:16, Catalog at:15, Sales at:15), and MMCA.Helpdesk has one (MMCA.Helpdesk/Source/Hosting/MMCA.Helpdesk.Migrations.SqlServer.Tickets/DesignTimeSQLServerDbContextFactory.cs:25). ADC'sDeleteBehaviorConventionTestsalso builds a design-time model to check delete behavior (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Domain/DeleteBehaviorConventionTests.cs). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/DesignTimeDbContextHelperTests.cs, which exercises the engines and the refresh-session gate, and by the per-gate model tests (ModelCacheKeyGateTests.cs,PasskeyModelGateTests.cs,MachineClientModelGateTests.cs,WebhookSubscriptionModelGateTests.cs). - Caveats / not-in-source: whether the flags in a given migrations project actually match that host's
appsettings.jsonis not checkable from this file; the guard isdotnet ef migrations has-pending-model-changes, named in the options remarks (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextOptions.cs:70-71).
IEntityTypeConfigurationBase<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/IEntityTypeConfigurationBase.cs:14· Level 4 · interface (public)
- What it is: the root of this framework's entity-configuration interface family. It extends EF Core's own
IEntityTypeConfiguration<TEntity>and redeclaresConfigurewith thenewmodifier, so the three engine-specific marker interfaces below it can redeclare it in turn (IEntityTypeConfigurationBase.cs:14-18). - Depends on: EF Core's
IEntityTypeConfiguration<TEntity>andEntityTypeBuilder<TEntity>(NuGet,IEntityTypeConfigurationBase.cs:1-2);AuditableBaseEntity<TIdentifierType>as the entity constraint (IEntityTypeConfigurationBase.cs:15). - Concept introduced, a marker-interface family used as a discovery filter. EF Core has exactly one configuration contract,
IEntityTypeConfiguration<TEntity>, andModelBuilder.ApplyConfigurationaccepts it. That is enough when a solution has one model. This framework builds one model per physical data source and has to answer a different question first: which configurations belong in this engine's model. The answer is a family of interfaces that all remain assignable to EF's contract (soApplyConfigurationstill accepts them) while carrying an engine tag in their type identity.ModelBuilderExtensions.ApplyAllConfigurationsscans an assembly for concrete types implementing the open generic interface it was handed, reads the entity type out of the interface's first generic argument, instantiates the configuration through DI, and invokesModelBuilder.ApplyConfiguration<TEntity>reflectively (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ModelBuilderExtensions.cs:42-64). This interface is the shared parent that keeps that whole scheme compatible with EF.[Rubric §2, Design Patterns]assesses whether a pattern earns its place; the marker interface here is not decoration, it is the type-level index the scan runs on.[Rubric §1, SOLID]assesses interface segregation and substitutability: every member of the family is still anIEntityTypeConfiguration<TEntity>, so nothing downstream of EF has to know the family exists. - Walkthrough
- Declaration (
IEntityTypeConfigurationBase.cs:14):IEntityTypeConfigurationBase<TEntity, TIdentifierType> : IEntityTypeConfiguration<TEntity>. Note the second type parameter, which EF's own contract does not have: it carries the identifier type so the constraint below can be expressed. - Constraints (
IEntityTypeConfigurationBase.cs:15-16):TEntity : AuditableBaseEntity<TIdentifierType>andTIdentifierType : notnull. Only audited entities are configurable through this family, which is why the base class can safely assume audit members exist. new void Configure(EntityTypeBuilder<TEntity> builder)(IEntityTypeConfigurationBase.cs:18): the redeclaration. The doc gives the reason directly (IEntityTypeConfigurationBase.cs:8-10): declaringConfigureexplicitly here is what lets the provider-specific interfaces redeclare it withnewas well. A single publicConfiguremethod on an implementing class satisfies every declaration in the chain.
- Declaration (
- Why it's built this way: the alternative is an attribute-only scheme, where every configuration is annotated and discovery is a reflection sweep over attributes. Putting the engine in the type system instead means the scan is a plain
GetInterfaces()match (ModelBuilderExtensions.cs:48-50), the compiler tells a consumer immediately when a configuration implements two engines' contracts, and the entity type is available as a generic argument rather than as something else to look up. - Where it's used: implemented by
EntityTypeConfigurationBase<TEntity, TIdentifierType>(EntityTypeConfigurationBase.cs:19-20) and extended by the three engine markers,IEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>,IEntityTypeConfigurationSqlite<TEntity, TIdentifierType>, andIEntityTypeConfigurationCosmos<TEntity, TIdentifierType>.
EntityTypeBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeBuilderExtensions.cs:14· Level 5 · class (public static, extension container)
- What it is: a generic
extension<TOwner>(EntityTypeBuilder<TOwner>)block with two members.OwnsMoney(...)maps aMoneyproperty as an owned type flattened into two columns on the owner's table: a decimal amount and an ISO 4217 currency code (EntityTypeBuilderExtensions.cs:14,:29-30, member at:66-99).OwnsAddress(...)does the same for anAddressproperty, flattened into six columns (:138-178). - Depends on:
MoneyandCurrencyfromMMCA.Common.Shared.ValueObjects,AddressandAddressInvariantsfrom the same namespace,UnknownStoredValuefor the read leg's rejection of an unknown stored code (EntityTypeBuilderExtensions.cs:89,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conversions/UnknownStoredValue.cs:24), EF Core'sEntityTypeBuilder<TEntity>andOwnsOne, andSystem.Linq.Expressions. - Concept introduced, the round-trip contract of a value converter.
[Rubric §4, Domain-Driven Design]assesses whether value objects survive the trip to storage intact, and[Rubric §15, Best Practices and Code Quality]assesses whether edge cases are handled where they arise. A value converter has two legs, write and read, and correctness means every value the write leg can produce is a value the read leg can materialize. The doc comment atEntityTypeBuilderExtensions.cs:38-49states that contract and draws the line between the two cases a stored code can fall into. An aggregate can seed a zero total withMoney.Zero(), whose currencyCodeis the empty string, and leave it there; the write leg persists that empty code faithfully, andCurrency.FromCode("")rejects it. That is a value the write leg genuinely produces, so the read leg maps an empty (or null) code back onto the "no currency" sentinel rather than letting it become anullCurrency inside aMoney. A non-empty code outsideCurrency.Allis different: the write leg cannot produce it (it was written outside EF, or the currency was removed after the rows were written), so the read leg throws anInvalidOperationExceptionnaming the code, the same verdict the JSON converter gives, instead of silently turning a foreign-currency amount into a currency-less one (:44-48). - Walkthrough
NoCurrency(EntityTypeBuilderExtensions.cs:27) is that sentinel, obtained asMoney.Zero().Currency. The comment at:22-26explains the indirection: the "no currency" instance is internal toMMCA.Common.Shared, so a zeroMoneyis the only public handle on it.- The extension is generic over the owner with a
classconstraint (EntityTypeBuilderExtensions.cs:29-30), so it applies to any entity that owns aMoney. - The signature takes the navigation expression, the two column names, and a
requiredflag defaulting totrue(EntityTypeBuilderExtensions.cs:66-70). The parameter doc at:59-64is honest about the design rule behind that:requiredis the only facet that differs across the existing call sites, so it is the only one parameterized beyond the two column names. - All four arguments are guarded, the strings with
ArgumentException.ThrowIfNullOrWhiteSpace(EntityTypeBuilderExtensions.cs:72-75). OwnsOnemaps the two members (EntityTypeBuilderExtensions.cs:77-94):Amountgets its column name, an explicitHasPrecision(18, 2)(:81, the SQL Server default made explicit so PostgreSQL and SQLite store and round amounts the same way; documented at:50-54) andIsRequired;Currencygets the two-leg conversion (:84-89): writecurrency => currency.Code; readNoCurrencywhenstring.IsNullOrEmpty(code), otherwiseCurrency.FromCode(code).Value ?? UnknownStoredValue.Throw<Currency>(code), plusHasMaxLength(3),IsUnicode(false), its column name, andIsRequired. That is the ISO 4217 code shape exactly: three non-Unicode characters.builder.Navigation(navigationExpression).IsRequired(required)(EntityTypeBuilderExtensions.cs:96) is a separate call from theOwnsOnebody because it configures the navigation rather than the owned entity's properties. The builder is returned for chaining (:98).OwnsAddress(...)(EntityTypeBuilderExtensions.cs:138-178) mapsAddress's six fields (AddressLine1,AddressLine2,City,State,ZipCode,Country) to columns built by the private helperAddressColumn(columnPrefix, propertyName)(:192-195). Each column iscolumnPrefix + propertyName, except the redundant leading wordAddressis dropped from the two line properties first (AddressPropertyPrefix,:20), so the default"Address"prefix yieldsAddressLine1/AddressLine2rather thanAddressAddressLine1/AddressAddressLine2, andAddressCity,AddressState,AddressZipCode,AddressCountryfor the rest; a second address on the same owner passes a differentcolumnPrefix(for example"ShippingAddress") and getsShippingAddressLine1,ShippingAddressCity, and so on. That is exactly the mapping the framework's own hand-written configurations already declared, so adopting the helper changes no column name, length or required-ness.- Max lengths on the six columns come from
AddressInvariants(EntityTypeBuilderExtensions.cs:151,156,160,164,168,172), the same constants theAddressvalue object validates against, so a column can never be shorter than what the domain accepts. NoIsUnicode(false)is applied: every column keeps the provider's Unicode default (nvarcharon SQL Server), becauseAddressaccepts free text in any script and a non-Unicode column would silently replace characters outside the database code page (doc comment at:118-126). OnlyAddressLine1is required, matching the value object, whose other five fields are optional for international address formats.requiredon the navigation itself defaults tofalse(:141), matching the existing call sites where an owner may have no address at all.
- Why it's built this way: value objects are validated primitives (ADR-068), which means construction is guarded but persistence must still round-trip every value that construction allowed, including the
Moneyzero sentinel, and must refuse a stored value construction could never have produced rather than invent a substitute. FlatteningMoneyinto two columns andAddressinto six on the owner's table rather than a separate table keeps a price, a total, or a location a single-row read. Putting each mapping behind one extension member means the read-leg sentinel and rejection rules forMoney, and the column-naming and invariant-length rules forAddress, are each written once and cannot be forgotten by the next configuration that maps one. - Where it's used:
OwnsMoneyhas three call sites, all in MMCA.Store's Sales and Catalog modules:MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Infrastructure/Persistence/EntityConfiguration/OrderConfiguration.cs:26(Total, withrequired: false),.../OrderLineConfiguration.cs:28(UnitPrice), andMMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Infrastructure/Persistence/EntityConfiguration/ProductVariantConfiguration.cs:31(Price); covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/OwnsMoneyTests.cs.OwnsAddressis covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/OwnsAddressTests.cs.
EntityTypeConfigurationBase<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfigurationBase.cs:19· Level 5 · class (public abstract)
- What it is: the engine-agnostic root class of the configuration hierarchy. It implements exactly one cross-cutting rule: an aggregate root's in-memory
DomainEventscollection must never be mapped to the database (EntityTypeConfigurationBase.cs:19-33). - Depends on:
IEntityTypeConfigurationBase<TEntity, TIdentifierType>(implements it,EntityTypeConfigurationBase.cs:20);AuditableBaseEntity<TIdentifierType>(constraint,:21);AuditableAggregateRootEntity<TIdentifierType>andIAggregateRoot(the runtime test and the ignored member,:29-31); EF Core'sEntityTypeBuilder<TEntity>(NuGet,:1). - Concept introduced, keeping a domain-only collection out of the model. An aggregate root collects domain events in memory so the dispatcher can drain them after a save. That collection is not state: it has no column, no table, and no meaning after the transaction closes. EF Core's convention-based model builder does not know that and would happily try to map it, which fails outright or (worse) invents a shadow table. One
builder.Ignorecall at the root of the hierarchy makes the exclusion automatic for every entity in every consumer, rather than a rule each configuration author has to remember.[Rubric §4, Domain-Driven Design]assesses whether the aggregate's event mechanism stays a domain concern; ignoring the collection is what keeps events a domain construct rather than a persisted one.[Rubric §9, API & Contract Design]assesses whether concerns that apply everywhere are handled once in a shared place; this is the smallest possible example of that, applied at the base class every configuration inherits. - Walkthrough
- Declaration (
EntityTypeConfigurationBase.cs:19-22): abstract, generic over the entity and its identifier type, implementing the base interface. Being abstract means it is never discovered as a configuration itself: the scan skips abstract types (ModelBuilderExtensions.cs:44). Configureisvirtual(EntityTypeConfigurationBase.cs:25): the derived engine-aware class overrides it and callsbase.Configure(builder)first, so this rule always runs before engine conventions (seeEntityTypeConfiguration<TEntity, TIdentifierType>,EntityTypeConfiguration.cs:41).- The aggregate-root test (
EntityTypeConfigurationBase.cs:29):typeof(IAggregateRoot).IsAssignableFrom(typeof(TEntity)). The rule is applied only to aggregate roots, because only they carry the collection; a plain child entity configured through the same hierarchy is untouched. - The exclusion (
EntityTypeConfigurationBase.cs:31):builder.Ignore(nameof(AuditableAggregateRootEntity<>.DomainEvents)). The unbound-genericnameofform is worth noticing: it names the member without having to close the generic, so the string stays refactor-safe. - What this class deliberately leaves to someone else (
EntityTypeConfigurationBase.cs:10-15): the doc records that entity-to-data-source mapping is not registered here as a model-building side effect.EntityDataSourceRegistryderives that mapping eagerly from the configuration class's attributes (UseDataSourceAttributefor the engine,UseDatabaseAttributeor the module namespace for the database), which is what lets routing be known before any model is built.
- Declaration (
- Why it's built this way: model building is the wrong place to accumulate a registry, because a model is built lazily and per data source, so "which entity lives where" would only be known after the first context of each kind had been constructed. Splitting the two (this class owns model rules, the registry owns routing) is what makes the routing table eagerly available at startup.
- Where it's used: extended by
EntityTypeConfiguration<TEntity, TIdentifierType>, and through it by every consumer configuration. Its two behaviors are pinned directly:Configure_AggregateRootEntity_ExcludesDomainEventsandConfigure_NonAggregateEntity_MapsEntity(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/EntityTypeConfigurationBaseTests.cs:18,:38).
IEntityTypeConfigurationCosmos<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/IEntityTypeConfigurationCosmos.cs:13· Level 5 · interface (internal)
- What it is: the engine marker for Azure Cosmos DB configurations (
IEntityTypeConfigurationCosmos.cs:13). It adds no members of its own beyond thenewredeclaration ofConfigure(:17); its whole job is to be the typeCosmosDbContextscans for. - Depends on:
IEntityTypeConfigurationBase<TEntity, TIdentifierType>(extends it,IEntityTypeConfigurationCosmos.cs:13);AuditableBaseEntity<TIdentifierType>(constraint,:14); EF Core'sEntityTypeBuilder<TEntity>(NuGet,:1). - Concept reinforced: the marker-interface-as-discovery-filter idea taught at
IEntityTypeConfigurationBase<TEntity, TIdentifierType>. The selection happens in oneswitchinsideApplicationDbContext:DataSource.CosmosDBmaps totypeof(IEntityTypeConfigurationCosmos<,>)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:1074), and that open generic is handed to the assembly scan. - Walkthrough
internal(IEntityTypeConfigurationCosmos.cs:13): unlike its parent, this interface is not part of the public API. Consumers are not meant to implement it directly; they derive fromEntityTypeConfigurationCosmos<TEntity, TIdentifierType>(or annotate withUseDataSourceAttribute), which implements it for them.new void Configure(...)(IEntityTypeConfigurationCosmos.cs:17): the redeclaration the base interface exists to enable.
- Caveats / not-in-source: implementing this interface directly, without the attributed base class, is a supported but degraded path.
EntityDataSourceRegistryskips configurations that carry noUseDataSourceAttribute(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/EntityDataSourceRegistry.cs:161-165), so such an entity lands in the engine's Default model but is not routable throughIUnitOfWork; the code comments call this legacy behavior (ApplicationDbContext.cs:1077-1081). - Where it's used: matched by
ApplicationDbContext.ApplyConfigurationsForEntitiesInContextfor the Cosmos engine (ApplicationDbContext.cs:1072-1079) and implemented byEntityTypeConfiguration<TEntity, TIdentifierType>(EntityTypeConfiguration.cs:32).
IEntityTypeConfigurationPostgreSQL<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/IEntityTypeConfigurationPostgreSQL.cs:13· Level 5 · interface (internal)
- What it is: the engine marker for PostgreSQL configurations (
IEntityTypeConfigurationPostgreSQL.cs:13), the fourth member of the marker-interface family alongside Cosmos, Sqlite, and SQL Server; structurally identical to its siblings. - Depends on:
IEntityTypeConfigurationBase<TEntity, TIdentifierType>(extends it,IEntityTypeConfigurationPostgreSQL.cs:13);AuditableBaseEntity<TIdentifierType>(constraint,:14); EF Core'sEntityTypeBuilder<TEntity>(NuGet,:1). - Concept reinforced: engine selection by interface identity, taught at
IEntityTypeConfigurationBase<TEntity, TIdentifierType>.DataSource.PostgreSQLmaps totypeof(IEntityTypeConfigurationPostgreSQL<,>)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:1075), the case added alongside the other three when PostgreSQL became a first-class engine (ADR-113). - Where it's used: matched by
PostgreSQLDbContextthrough the shared discovery method, and implemented byEntityTypeConfiguration<TEntity, TIdentifierType>(EntityTypeConfiguration.cs:30).
IEntityTypeConfigurationSqlite<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/IEntityTypeConfigurationSqlite.cs:13· Level 5 · interface (internal)
- What it is: the engine marker for SQLite configurations (
IEntityTypeConfigurationSqlite.cs:13), structurally identical to its Cosmos and SQL Server siblings. - Depends on:
IEntityTypeConfigurationBase<TEntity, TIdentifierType>(IEntityTypeConfigurationSqlite.cs:13);AuditableBaseEntity<TIdentifierType>(:14); EF Core'sEntityTypeBuilder<TEntity>(:1). - Concept reinforced: engine selection by interface identity, taught at
IEntityTypeConfigurationBase<TEntity, TIdentifierType>.DataSource.Sqlitemaps totypeof(IEntityTypeConfigurationSqlite<,>)(ApplicationDbContext.cs:1076). - Where it's used: matched by
SqliteDbContextthrough the shared discovery method, implemented byEntityTypeConfiguration<TEntity, TIdentifierType>(EntityTypeConfiguration.cs:31), and used directly by the framework's own tests as the scan target: theApplyAllConfigurationstests passtypeof(IEntityTypeConfigurationSqlite<,>)as the interface to match (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/ModelBuilderExtensionsTests.cs:93,:148), and two test types implement it directly to exercise the unattributed path (ModelBuilderExtensionsTests.cs:108,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/EntityDataSourceRegistryTests.cs:233).
IEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/IEntityTypeConfigurationSQLServer.cs:13· Level 5 · interface (internal)
- What it is: the engine marker for SQL Server configurations (
IEntityTypeConfigurationSQLServer.cs:13). It is the one of the three that matters in production today, because every deployed entity in ADC and Store routes to SQL Server. - Depends on:
IEntityTypeConfigurationBase<TEntity, TIdentifierType>(IEntityTypeConfigurationSQLServer.cs:13);AuditableBaseEntity<TIdentifierType>(:14); EF Core'sEntityTypeBuilder<TEntity>(:1). - Concept reinforced: engine selection by interface identity.
DataSource.SQLServermaps totypeof(IEntityTypeConfigurationSQLServer<,>)(ApplicationDbContext.cs:1077); anything the switch does not recognize throwsInvalidOperationExceptionrather than silently building an empty model (ApplicationDbContext.cs:1078). - Where it's used: matched by
SQLServerDbContextthroughApplyConfigurationsForEntitiesInContext, and implemented byEntityTypeConfiguration<TEntity, TIdentifierType>(EntityTypeConfiguration.cs:29), which is how all 28 ADC configurations and all 12 Store configurations reach it through theEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>shim.
MachineClientModelBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.MachineClients·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/MachineClientModelBuilderExtensions.cs:17· Level 5 · class (public static)
- What it is: the one place the
MachineClienttable (OAuth client-credentials clients, ADR-140) is mapped into an EF Core model. A single extension method,ApplyMachineClientConfiguration, plus two public name constants, the table nameMachineClientsand the unique index nameIX_MachineClients_ServiceAccountUserId(MachineClientModelBuilderExtensions.cs:17-23, method at:28-52). - Depends on:
MachineClient(the mapped entity and itsNameMaxLength,MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClient.cs:24);MachineClientSecret(HashByteLength,MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClientSecret.cs:21); EF Core'sModelBuilder(NuGet,MachineClientModelBuilderExtensions.cs:1). - Concept reinforced, an opt-in framework table gated per data source. The gated-table shape is the one the passkey table set first (
PasskeyCredentialModelBuilderExtensions), and the class doc names it as the precedent (MachineClientModelBuilderExtensions.cs:11-16):ApplicationDbContextapplies this mapping only to the one context whose physical source is named byMachineClients:DataSourceName(defaultDefault,MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientSettings.cs:48) and only whileMachineClients:Enabledis true (:36), so a host that never opts in keeps a byte-identical model and needs no migration (the gate isMachineClientModelContributor.AppliesTo,MachineClientModelBuilderExtensions.cs:77-79; the context keeps only the contributors that apply to its source,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:550-554, and runs them at:431). The applying contributor types also form the context'sModelContributorKey(ApplicationDbContext.cs:114-115), so a context with the table and one without never share a cached model.[Rubric §8, Data Architecture]assesses whether each table has a deliberate home; the machine-client table lives in exactly one named database (in practice the Identity one) rather than in every module's.[Rubric §15, Best Practices & Code Quality]assesses whether optional features cost nothing when off; a disabled host carries no table, no index and no migration. - Walkthrough
TableNameandServiceAccountIndexName(MachineClientModelBuilderExtensions.cs:20,:18): public constants so tests and migrations name the same strings the mapping uses; the model gate test asserts the table name throughTableName(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/MachineClients/MachineClientModelGateTests.cs:86).ApplyMachineClientConfiguration(modelBuilder, schema = "dbo")(MachineClientModelBuilderExtensions.cs:33-35): null-guards the builder; thedbodefault matches the framework's own tables (:26).- Key (
MachineClientModelBuilderExtensions.cs:39-41):ToTable(TableName, schema),HasKey(e => e.Id)andValueGeneratedNever(), so the client id the domain assigns is the id stored. - Columns (
MachineClientModelBuilderExtensions.cs:43-48):Nameis required withMachineClient.NameMaxLength(100);PrimarySecretHashis required andSecondarySecretHashoptional, both capped atMachineClientSecret.HashByteLength(32 bytes), which is the point: only a fixed-length hash is stored, never the secret.SecretExpiresOn,RevokedOnandLastUsedOnmap by convention. Ignore(e => e.IsRevoked)(MachineClientModelBuilderExtensions.cs:50):IsRevokedis computed fromRevokedOn(MachineClient.cs:54), so it has no column.- Unique index on
ServiceAccountUserId(MachineClientModelBuilderExtensions.cs:52-53): one client per service account, because the account's role is the client's whole authority (the inline comment). The index is not hand-filtered here; soft-delete filtering of unique indexes is the job ofSoftDeleteUniqueIndexConvention.
- Why it's built this way: the doc on the method requires it to run BEFORE the soft-delete, tenant and concurrency-token passes (
MachineClientModelBuilderExtensions.cs:25-28), andOnModelCreatinghonors that by running theBeforeEntityPassescontributors, this mapping's among them, ahead ofApplySoftDeleteFilters,ApplyTenantFiltersandConfigureConcurrencyTokens(ApplicationDbContext.cs:644-653). A client is an auditable entity, so those passes give it theIsDeletedfilter and the concurrency token like any other entity; the gate test pins the soft-delete column and query filter (MachineClientModelGateTests.cs:88-89). - Where it's used: called only from
MachineClientModelContributor.Configure(MachineClientModelBuilderExtensions.cs:83), whichApplicationDbContext.OnModelCreatingruns in itsBeforeEntityPassescontributor call (ApplicationDbContext.cs:649). Covered byMachineClientModelGateTests: the table is in the named source's model and absent from another (MachineClientModelGateTests.cs:39-47), and the design-time path includes it only withDesignTimeDbContextOptions.EnableMachineClients(:52-70; seeDesignTimeDbContextOptions). Read and written at runtime throughEFMachineClientStore.
IndexBuilderExtensions
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/IndexBuilderExtensions.cs:10· Level 2 · class (public static, extension container)
- What it is: a single C#
extension(IndexBuilder)block exposing one member,HasSoftDeleteFilter(...), which attaches theIsDeleted = 0predicate to a hand-authored index in an entity type configuration (IndexBuilderExtensions.cs:10-12, member at:50-64). - Depends on:
SoftDeleteFilterSql(the shared predicate builder,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SoftDeleteFilterSql.cs:28), theDataSourceengine enum, and EF Core'sMicrosoft.EntityFrameworkCore.Metadata.Builders.IndexBuilder. - Concept introduced, the filtered (partial) index under soft delete.
[Rubric §8, Data Architecture]assesses whether the storage design accounts for the consequences of its own conventions, and[Rubric §12, Performance and Scalability]assesses whether indexes match the queries they serve. Soft delete (ADR-005) means a "deleted" row is still physically present withIsDeleted = 1, and the global query filter onApplicationDbContexthides it from every read. An index that does not carry the same predicate therefore indexes rows no query will ever return: the deleted rows still occupy index pages, and the optimizer's row estimates include them. The doc comment states this in one sentence (IndexBuilderExtensions.cs:14-18). AddingWHERE [IsDeleted] = 0to the index makes it a filtered index (SQL Server's term; SQLite calls the same thing a partial index) that matches the shape of every query the application actually issues. - Walkthrough
- The extension receiver is the
IndexBuilderreturned bybuilder.HasIndex(...), so the call chains directly off the index declaration (IndexBuilderExtensions.cs:12, usage sample at:23-26). enginedefaults toDataSource.SQLServer(IndexBuilderExtensions.cs:53), which matches the majority case of a configuration deriving fromEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>; a SQLite or PostgreSQL configuration passesDataSource.SqliteorDataSource.PostgreSQLexplicitly. PostgreSQL needs it for a real reason, not just symmetry: its soft-delete flag is a genuine boolean column, so the predicate the engine produces is"IsDeleted" = falserather than SQL Server's[IsDeleted] = 0(IndexBuilderExtensions.cs:37-43).additionalFilteris the optional second predicate for an index that is already conditional on something else, for example"[ExternalSessionId] IS NOT NULL"(IndexBuilderExtensions.cs:45-50). The two are joined as{additionalFilter} AND {filterSql}in that exact order (:62-65), which is deliberate: it reproduces the SQL of the hand-authored literal the helper replaced, so switching to the helper does not force a migration. It is also the orderSoftDeleteUniqueIndexConventionuses when it appends its own clause, so the two paths yield byte-identical SQL for the same pair of predicates.- The body null-guards the receiver, asks
SoftDeleteFilterSqlto build the predicate from the model's own metadata, and returns the builder unchanged when the builder returnsnull(IndexBuilderExtensions.cs:56-60). Thatnullis the Cosmos no-op and the "this entity is not soft-deletable" case, so the call is always safe to write.
- The extension receiver is the
- Why it's built this way: the doc comment gives the rationale directly (
IndexBuilderExtensions.cs:27-29). A literalHasFilter("[IsDeleted] = 0")hard-codes both the column name and SQL Server's bracket quoting; reading the column name from the model means aHasColumnNamerename follows automatically, and delegating the quoting to the engine keeps the same configuration body valid on SQLite. This is the portability posture of ADR-018. The division of labour withSoftDeleteUniqueIndexConventionis explicit: the convention covers every UNIQUE index automatically, and this extension point exists for the case the convention deliberately leaves alone, a hand-authored NON-unique index (IndexBuilderExtensions.cs:20-22). The pair of them is ADR-095. - Where it's used: entity configurations across both applications. In MMCA.Store:
MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Infrastructure/Persistence/EntityConfiguration/OrderConfiguration.cs:44,51,58(the last one withadditionalFilter: "[StripeSessionId] IS NOT NULL"),MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:69,83,.../EntityConfiguration/CustomerConfiguration.cs:82,MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Infrastructure/Persistence/EntityConfiguration/ProductConfiguration.cs:43,.../ProductImageConfiguration.cs:54,.../ProductVariantConfiguration.cs:46,.../CategoryConfiguration.cs:33. In MMCA.ADC's Engagement module:MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Persistence/EntityConfiguration/CheckIns/CheckInConfiguration.cs:52,57,63,67,70,.../PointsEntryConfiguration.cs:48,52,.../LivePollVoteConfiguration.cs:37,.../LeaderboardOptInConfiguration.cs:35,.../SessionQuestionUpvoteConfiguration.cs:34,.../UserSessionBookmarkConfiguration.cs:34,39. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/IndexBuilderExtensionsTests.cs. - Caveats / not-in-source: the ordering constraint is called out in the doc comment (
IndexBuilderExtensions.cs:31-35). Unlike the convention, which runs at model finalizing, this member reads the column name at the moment it is called, so aHasColumnNameon the soft-delete property must be declared before the index. That only bites a model that renames the column.
EntityTypeConfiguration<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfiguration.cs:27· Level 9 · class (public abstract)
- What it is: the engine-aware configuration base and the busiest type in this family. It reads the target engine off a
UseDataSourceAttributeon the concrete configuration class (or on an inherited shim base) and hands that engine's table/container mapping plus key generation to the matching engine strategy, so a consumer'sConfigurebody only ever describes columns, indexes, and relationships (EntityTypeConfiguration.cs:27-80). It also exposesEffectiveEngine, the engine of the model actually being built, for the few configurations that write engine-specific SQL text themselves (:54-61). - Depends on:
EntityTypeConfigurationBase<TEntity, TIdentifierType>(base,EntityTypeConfiguration.cs:28); all four engine markers,IEntityTypeConfigurationSQLServer<TEntity, TIdentifierType>,IEntityTypeConfigurationPostgreSQL<TEntity, TIdentifierType>,IEntityTypeConfigurationSqlite<TEntity, TIdentifierType>,IEntityTypeConfigurationCosmos<TEntity, TIdentifierType>(:29-32);AuditableBaseEntity<TIdentifierType>as the entity constraint (:4,:33);UseDataSourceAttributeand theDataSourceenum (:3,:43,:61,:70);DataSourceEngines(:5,:78), which returns the registeredIDataSourceEnginefor an engine value (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/DataSourceEngines.cs:40-43); the internalEngineAnnotationconstant ofApplicationDbContext(:48,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:65);System.Reflectionand EF Core'sEntityTypeBuilder<TEntity>(:1-2). - Concept introduced, one configuration body that is portable across storage engines. The naive way to support four engines is four configuration classes per entity, or one class littered with
if (engine == ...). This class removes both. The engine is declared once, as an attribute, and everything that actually differs between engines is owned by one strategy per engine: this class looks the strategy up withDataSourceEngines.For(engine)and calls itsApplyKeyAndTableMapping(EntityTypeConfiguration.cs:78,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/IDataSourceEngine.cs:95).SQLServerDataSourceEngineandPostgreSQLDataSourceEngineapply the identical mapping, a table in a module schema (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:100-106,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/PostgreSQLDataSourceEngine.cs:98-101);SqliteDataSourceEnginegives a bare table, since SQLite has no schemas (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SqliteDataSourceEngine.cs:97-102);CosmosDataSourceEnginegives a per-module container with the entity id as partition key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/CosmosDataSourceEngine.cs:92-101). Moving an entity from SQL Server to Cosmos, or from SQL Server to PostgreSQL, is therefore a one-line attribute change. Two other pieces of the framework complete the portability claim rather than this class alone:CosmosDbContextstrips every relational index from the built model, because the Cosmos provider rejects them and indexes every property itself (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/CosmosDbContext.cs:129-137), andCrossDataSourceDegradeConventionremoves FK constraints and navigations that would span physical sources while keeping the declared scalar FK column and a compensating index (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/CrossDataSourceDegradeConvention.cs:10-22). A dedicated test builds a Cosmos model offline from a configuration that keeps a filtered index and a cross-source relationship, and asserts the indexes are gone, the FK is gone, the scalar FK column survives, and the foreign principal is not in the model (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/CosmosConfigurationPortabilityTests.cs:70-76).[Rubric §8, Data Architecture]assesses how deliberately the storage shape is chosen and how tightly the model is bound to one engine.[Rubric §7, Microservices Readiness]assesses whether a module can be lifted out without a rewrite; being able to re-point an entity's engine and database with attributes is a precondition for that (ADR-018, ADR-006, ADR-113).[Rubric §15, Best Practices & Code Quality]assesses whether one decision lives in one place; each engine's mapping lives in exactly one strategy, and this file names no concrete engine value at all. That last property is enforced:DataSourceBranchingFitnessTestsscansSource/**/*.csand fails on any concrete engine named outside an exact allow-list, which lists the four shim bases but not this class (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/DataSourceBranchingFitnessTests.cs:24-66,:71-80; ADR-130). - Concept introduced, discovery and routing that agree by construction. This class implements all four engine marker interfaces (
EntityTypeConfiguration.cs:29-32), so a configuration derived from it is discovered during every engine's model pass. That sounds wrong until you see the filter:ApplyConfigurationsForEntitiesInContextapplies a discovered configuration only whenEntityDataSourceRegistrysays the entity'sDataSourceKeyequals this context instance's key (ApplicationDbContext.cs:1098-1100). Both sides read the same attributes: the registry derives the engine fromUseDataSourceAttributeand the logical database fromUseDatabaseAttribute, falling back to the entity's module namespace and then toDefault(EntityDataSourceRegistry.cs:167-169), while this class reads the same attribute for its conventions. Discovery is broad, routing is exact, and there is no second source of truth to drift.[Rubric §1, SOLID]assesses whether behavior is driven from one declaration; here the attribute is that declaration. - Concept introduced, declared engine versus effective engine. The declared engine and the engine of the model being built usually agree, but not always: when a host substitutes an unconfigured engine (the doc comment's example is a SQL Server configuration applied to a PostgreSQL-only host), the configuration's own attribute is the wrong input for hand-written SQL such as an index filter (
EntityTypeConfiguration.cs:54-60).ApplyConfigurationsForEntitiesInContexttherefore stamps the context's engine onto the model as an annotation for the duration of the configuration pass and removes it in afinally, so the finished model and every migration snapshot are unchanged (ApplicationDbContext.cs:1084-1089,:983-986).Configurecopies that annotation intoEffectiveEngine, falling back to the declared engine when no annotation is present (EntityTypeConfiguration.cs:48-49). The key and table mapping still uses the declared engine (:51);EffectiveEngineis for SQL text only. The framework's own consumers show the use:PushNotificationConfigurationbuilds a filtered unique index whose predicate is quoted forEffectiveEnginethroughSoftDeleteFilterSql(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/PushNotificationConfiguration.cs:82-83), andUserNotificationConfigurationpasses it toHasSoftDeleteFilter(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/UserNotificationConfiguration.cs:45). - Walkthrough
- Declaration (
EntityTypeConfiguration.cs:27-34): abstract, extends the base class, implements the four markers, constrained to an audited entity with a non-null identifier type. Configureoverride (EntityTypeConfiguration.cs:37-52): null-guards the builder (:39), callsbase.Configure(builder)so theDomainEventsexclusion runs first (:41), then reads the engine.- The attribute read and its failure mode (
EntityTypeConfiguration.cs:43-46):GetType().GetCustomAttribute<UseDataSourceAttribute>()?.DataSourceon the runtime type, which is the concrete configuration.UseDataSourceAttributeis declared withInherited = true(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/UseDataSourceAttribute.cs:13), which is exactly why a class deriving from one of the shim bases inherits its engine without repeating the annotation. When the attribute is missing entirely the code throwsInvalidOperationExceptionnaming the offending configuration class, rather than defaulting to an engine and mapping the entity somewhere surprising. EffectiveEngine(EntityTypeConfiguration.cs:48-49,:61):protectedwith aprivate set, assigned from the model's engine annotation or the declared engine, thenApplyEngineConventions(builder, engine)runs with the declared engine (:51). The doc comment states it is valid insideConfigureafter the base call (:58-59).ApplyEngineConventions(builder, engine),protected static(EntityTypeConfiguration.cs:70-79): called fromConfigure; the doc comment states that the provider shim bases inherit it rather than calling it themselves (:63-66). After its own null guard (:72) it is a single delegation,DataSourceEngines.For(engine).ApplyKeyAndTableMapping<TEntity, TIdentifierType>(builder)(:78); the inline comment records that each engine owns its mapping, that PostgreSQL takes the SQL Server mapping unchanged, module schema and PascalCase identifiers included, so an entity moves between the two by changing its configuration base class and nothing else (ADR-113), and that Cosmos puts a module's entities in one container partitioned by id (:74-77). An engine value with no registered strategy throwsInvalidOperationException("DataSource ... not implemented") fromDataSourceEngines.Forinstead of silently producing an unmapped entity (DataSourceEngines.cs:40-43).- What the strategies apply: every engine calls
HasKey(p => p.Id)and readstypeof(TEntity).IsIdValueGenerated, the presence test forIdValueGeneratedAttributeviaEntityTypeExtensions(MMCA.Common/Source/Core/MMCA.Common.Domain/Extensions/EntityTypeExtensions.cs:48-50). SQL Server and PostgreSQL mapToTable(entityName, moduleName ?? "dbo"), so the SQL schema is the module name derived from the entity namespace and unmoduled entities land indbo, thenValueGeneratedOnAdd()when the entity opts into generated ids andValueGeneratedNever()otherwise (SQLServerDataSourceEngine.cs:101-106). That last branch is what lets a domain factory assign an id itself without EF overwriting it. SQLite mapsToTable(entityName)with no schema and adds.UseIdentityColumn(1, 1)in the generated-id case (SqliteDataSourceEngine.cs:97-102). Cosmos mapsToContainer(moduleName ?? entityName).HasPartitionKey(p => p.Id)withValueGeneratedNever(), and refuses an entity marked[IdValueGenerated]with anInvalidOperationExceptionat model build, because Cosmos generates no keys and a client-side counter cannot be unique across instances (CosmosDataSourceEngine.cs:98-113). NamespaceConventions.GetModuleName(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/NamespaceConventions.cs:20-21): an internal one-line delegation toModuleNameConventions.GetModuleName, documented as taking the namespace segment immediately precedingDomain(MMCA.Store.Sales.Domain.OrdersyieldsSales) and returningnullwhen there is noDomainsegment (NamespaceConventions.cs:13-19). The engine strategies use it for the schema and container name (SQLServerDataSourceEngine.cs:101,CosmosDataSourceEngine.cs:110), and the same helper feeds the logical database name in the registry (EntityDataSourceRegistry.cs:168), which is the point of it being shared: schema and database name can never drift apart.
- Declaration (
- Why it's built this way: the framework's stated multi-database model is one context class per engine and one instance per database (ADR-006), with the engine as an orthogonal axis (ADR-018). That only works if the mapping conventions for an engine live in one place that every context can call. This class is the single entry point and the engine strategy is that place (ADR-130), so adding an engine means one more strategy in the
DataSourceEnginesregistry (DataSourceEngines.cs:22-28) rather than an edit here. BecauseConfigureitself reads the engine attribute and callsApplyEngineConventions, the shims inherit the whole behavior and exist as empty declarations that only carry the attribute. - Where it's used: extended by the four shim bases below (
EntityTypeConfigurationSQLServer<TEntity, TIdentifierType>,EntityTypeConfigurationPostgreSQL<TEntity, TIdentifierType>,EntityTypeConfigurationSqlite<TEntity, TIdentifierType>,EntityTypeConfigurationCosmos<TEntity, TIdentifierType>), and directly by any configuration that prefers to carry its own[UseDataSource(...)]annotation, as one portability test does (CosmosConfigurationPortabilityTests.cs:101-103).EffectiveEngineis read by the framework's notification configurations (PushNotificationConfiguration.cs:82-83,UserNotificationConfiguration.cs:45). Its conventions are pinned against a real SQLite model inSqliteConfig_Configure_SetsTableNameAndKeyandSqliteConfig_Configure_SetsValueGeneratedNever_WhenNoAttribute(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/EntityTypeConfigurationTests.cs:22,:37).
MachineClientModelContributor
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.MachineClients·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/MachineClientModelBuilderExtensions.cs:71· Level 9 · class (internal sealed)
- What it is: the
IModelContributorthat puts theMachineClientstable into a context's model. It decides which physical source gets the table and then callsMachineClientModelBuilderExtensions.ApplyMachineClientConfiguration(MachineClientModelBuilderExtensions.cs:71-84). It shares the file of the extension class it applies. - Depends on:
IOptions<MachineClientSettings>as its one primary-constructor parameter (MachineClientModelBuilderExtensions.cs:71), plusIModelContributor,ModelContributorPhase,PhysicalDataSourceandDataSource. - Concept reinforced: the optional framework table as a registered contributor, taught at
PasskeyCredentialModelContributor. The shape is the same; the phase is the one difference that matters.[Rubric §8, Data Architecture]assesses whether each database holds exactly the data it owns: the gate answers "does this source get the table" once, inAppliesTo. - Walkthrough
PhaseisBeforeEntityPasses(MachineClientModelBuilderExtensions.cs:74), unlike the passkey, refresh-session, permission-grant and view-as contributors, which run after. The class doc gives the reason (:66-67): aMachineClientis an auditable entity, so the soft-delete filter and the concurrency token must see it.ApplicationDbContext.OnModelCreatingruns theBeforeEntityPassescontributors ahead ofApplySoftDeleteFiltersandConfigureConcurrencyTokens(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:649-653), which is the ordering the extension method's own doc requires (MachineClientModelBuilderExtensions.cs:25-28).AppliesTo(MachineClientModelBuilderExtensions.cs:77-79) holds only whileMachineClients:Enabledis true AND the source'sKey.NameequalsMachineClients:DataSourceNameunder ordinal comparison.Configure(MachineClientModelBuilderExtensions.cs:82-83) ignores the engine and callsApplyMachineClientConfiguration()with its defaultdboschema.
- Why it's built this way: ADR-148 moves every optional framework table onto the contributor extension point, and machine clients are opt-in (ADR-140). The class doc states the outcome (
MachineClientModelBuilderExtensions.cs:60-64): a host that registers the feature without enabling it, or any database other than the owning one, sees no migration. - Where it's used: registered with
TryAddEnumerableas a singletonIModelContributorbyAddMachineClients, with the comment that it is inert untilMachineClients:Enabledand then only on the named source (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.MachineClients.cs:48-50); added at design time whenDesignTimeDbContextOptions.EnableMachineClientsis set (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:206). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/MachineClients/MachineClientModelGateTests.cs,.../DependencyInjectionModelContributorTests.csand.../Persistence/DataSources/ModelCacheKeyGateTests.cs.
EFMachineClientStore
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.MachineClients·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/EFMachineClientStore.cs:28· Level 13 · class (internal sealed)
- What it is: the EF Core implementation of
IMachineClientStore, the persistence port behind machine-client (OAuth client credentials) issuance and administration (ADR-140). It lists, finds, adds and savesMachineClientrows and records each client's last use (EFMachineClientStore.cs:12-27,:28-90). - Depends on:
IDbContextFactory,IEntityDataSourceRegistry,IDataSourceResolverandIOptions<MachineClientSettings>(MachineClientSettings) as primary-constructor parameters (EFMachineClientStore.cs:28-32);ApplicationDbContext,DataSourceKeyandFrameworkTableTargets(:34,:87-89); EF Core'sDbSet<T>,AsNoTrackingandDbUpdateConcurrencyException(NuGet,:1). - Concept reinforced, a framework-owned store that finds its own database. The class doc names
EFPasskeyCredentialStoreas the precedent (EFMachineClientStore.cs:15-16), and the resolution itself is no longer written in this class:ResolveDataSourceKeydelegates toFrameworkTableTargets.ResolveHome<MachineClient>, the one resolution every store and sweep over this table shares (:87-89), so a sweep can never visit a different database than this store reads (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:90-91).ResolveHomeasks theEntityDataSourceRegistryfor the entity type first; when the entity is not registered (it is mapped byMachineClientModelBuilderExtensions, not by an attributed configuration) it builds aDataSourceKeyfrom the default logical source's engine and the configuredMachineClients:DataSourceName, used verbatim (FrameworkTableTargets.cs:105-113, remarks at:94-96). TheDataSource.SQLServerliteral that request carries now lives inResolveHome(FrameworkTableTargets.cs:112), is a request for the framework default resolved through the resolver, and is listed as such in theDataSourceBranchingFitnessTestsallow-list againstFrameworkTableTargets.cs(MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/DataSourceBranchingFitnessTests.cs:63). Because the key matches the one context whose model carries the table (see the gate atMachineClientModelBuilderExtensions), the store never queries a database without the table.[Rubric §8, Data Architecture]assesses whether data has one owning store per service; the client table lives in one named database and every read and write goes to it.[Rubric §11, Security]assesses whether credential handling is deliberate; writes go through the context's save path so the audit interceptor stamps who created, rotated or revoked a client (:19-21). - Walkthrough
ContextandClients(EFMachineClientStore.cs:34,:36): private properties that resolve theApplicationDbContextfor the resolved key throughIDbContextFactory.GetDbContexton each access, and itsSet<MachineClient>().ListAsync(EFMachineClientStore.cs:39-44):AsNoTracking, ordered byCreatedOn, for the administration listing.FindAsync(clientId)(EFMachineClientStore.cs:47-48): a trackedFirstOrDefaultAsyncby id. Tracked on purpose: the later save depends on it.AddAsync(client)(EFMachineClientStore.cs:51-57): guards, adds to the set, then saves throughdbContextFactory.SaveChangesAsync.SaveAsync(client)(EFMachineClientStore.cs:60-67): only a save. The comment explains why (:64-65): the row came fromFindAsync, which tracks it, so the context already knows the change.RecordUseAsync(client, usedOn)(EFMachineClientStore.cs:70-85): calls the domain'sRecordUse, which setsLastUsedOn(MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClient.cs:177), and saves, swallowingDbUpdateConcurrencyException(:79-84). The comment gives the reasoning: a concurrent issuance for the same client moved the row version first, itsLastUsedOnis as good as this one, and the token is already minted, so the conflict is dropped rather than failing the calling program's request.ResolveDataSourceKey()(EFMachineClientStore.cs:88-89): a one-line delegation toFrameworkTableTargets.ResolveHome<MachineClient>(registry, dataSourceResolver, settings.Value.DataSourceName), described above; only the engine goes through the resolver, the name is the setting (FrameworkTableTargets.cs:94).
- Why it's built this way: the store is
internaland registered only byAddMachineClientsas a scopedTryAddScoped<IMachineClientStore, EFMachineClientStore>, sharing the request's Identity context with the provisioner the app registers (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.MachineClients.cs:52-53). Every caller sits behind theMachineClients:Enabledgate (EFMachineClientStore.cs:19-20), which is the same switch that decides whether the table is in the model, so the port and the table appear and disappear together. - Where it's used: resolved as
IMachineClientStorebyMachineClientService(registered beside it,DependencyInjection.MachineClients.cs:54).EFWebhookSubscriptionStorenames it as the precedent for its own database resolution (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Webhooks/EFWebhookSubscriptionStore.cs:16). - Caveats / not-in-source: whether a test exercises the swallowed concurrency conflict in
RecordUseAsyncis not determinable from the sources read for this section.
EntityTypeConfigurationCosmos<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfigurationCosmos.cs:18· Level 7 · class (public abstract)
- What it is: a body-less shim over
EntityTypeConfiguration<TEntity, TIdentifierType>whose only content is the class-level[UseDataSource(DataSource.CosmosDB)]annotation (EntityTypeConfigurationCosmos.cs:17-21). Deriving from it is equivalent to deriving from the engine-aware base and annotating the concrete class by hand, as its own doc says (EntityTypeConfigurationCosmos.cs:10-13). - Depends on:
EntityTypeConfiguration<TEntity, TIdentifierType>(base,EntityTypeConfigurationCosmos.cs:19);UseDataSourceAttributeand theDataSourceenum (:1,:17);AuditableBaseEntity<TIdentifierType>(constraint,:20). - Concept reinforced, an attribute expressed as a base class. All mapping logic (per-module container, entity-id partition key, and the refusal of
[IdValueGenerated]ids, since a Cosmos entity assigns its own,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/CosmosDataSourceEngine.cs:98-113) lives in the engine-aware base; this type exists so the engine choice reads as part of the class declaration a consumer already writes, and soInherited = trueon the attribute (UseDataSourceAttribute.cs:13) carries it to the concrete class. The declaration ends in a semicolon (EntityTypeConfigurationCosmos.cs:21): there is genuinely no body. - Where it's used: no configuration in MMCA.Common, MMCA.ADC, MMCA.Store, or the Common test suite derives from it today. The Cosmos path is exercised instead through a direct
[UseDataSource(DataSource.CosmosDB)]annotation on a configuration deriving from the engine-aware base (CosmosConfigurationPortabilityTests.cs:101-103), and the Aspire hosting extensions name the type when documenting which entities a Cosmos data source will serve (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/Extensions.cs:634). This matches the state ADR-018 records: the plumbing ships and is tested, with no non-SQL entity in production today.
EntityTypeConfigurationPostgreSQL<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfigurationPostgreSQL.cs:22· Level 7 · class (public abstract)
- What it is: the PostgreSQL shim,
[UseDataSource(DataSource.PostgreSQL)]over the engine-aware base (EntityTypeConfigurationPostgreSQL.cs:21-25). Its own doc records that the mapping it produces is the SQL Server one, not PostgreSQL house style: a table per entity inside the module schema with an identity key, so an entity moves between the two engines with a single base-class change and no configuration-body edits (:6-17). - Depends on:
EntityTypeConfiguration<TEntity, TIdentifierType>(base,EntityTypeConfigurationPostgreSQL.cs:23);UseDataSourceAttributeandDataSource(:21);AuditableBaseEntity<TIdentifierType>(:24). - Concept reinforced: the attribute-as-base-class shim taught at
EntityTypeConfigurationCosmos<TEntity, TIdentifierType>. The engine-aware base hands the table/key mapping to the target engine (DataSourceEngines.For(engine).ApplyKeyAndTableMapping,EntityTypeConfiguration.cs:74-78), and the PostgreSQL engine's implementation is deliberately identical to SQL Server's: a table named for the entity in the module schema (falling back todbo), theIdkey, and store generation only when the identifier type is value-generated (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/PostgreSQLDataSourceEngine.cs:92-106). PostgreSQL house style (snake_case identifiers, thepublicschema) is left to a consumer's own naming-convention plugin rather than built into the framework (ADR-113,EntityTypeConfiguration.cs:74-77). - Where it's used: exercised by the framework's own PostgreSQL test suite,
PostgreSQLPersistenceTests.cs,DesignTimeDbContextHelperTests.cs, andPostgreSQLDbContextModelTests.cs(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.PostgreSQL.Tests/andMMCA.Common.Infrastructure.Tests/). No production configuration in ADC, Store, or Helpdesk derives from it today, matching the state ADR-113 records: the engine is plumbed and tested, with no PostgreSQL entity shipped in either app yet.
EntityTypeConfigurationSqlite<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfigurationSqlite.cs:17· Level 7 · class (public abstract)
- What it is: the SQLite shim, identical in shape to its Cosmos sibling: a body-less class carrying
[UseDataSource(DataSource.Sqlite)](EntityTypeConfigurationSqlite.cs:16-20). - Depends on:
EntityTypeConfiguration<TEntity, TIdentifierType>(base,EntityTypeConfigurationSqlite.cs:18);UseDataSourceAttributeandDataSource(:1,:16);AuditableBaseEntity<TIdentifierType>(:19). - Concept reinforced: the attribute-as-base-class shim taught at
EntityTypeConfigurationCosmos<TEntity, TIdentifierType>. Its doc records the SQLite-specific mapping it delegates: table name plus an auto-increment key (EntityTypeConfigurationSqlite.cs:7-12), which the engine-aware base hands to the SQLite engine (EntityTypeConfiguration.cs:78), implemented atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SqliteDataSourceEngine.cs:91-103. - Where it's used: no production configuration in the three repos derives from it, but it is the framework's own in-memory-and-file test engine and is used throughout the Common test suite: the database-initialization tests (
MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/DatabaseInitializationExtensionsTests.cs:321,:279), the convention tests (EntityTypeConfigurationTests.cs:58), the multi-source integration tests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/MultiSourceSqliteIntegrationTests.cs:240,:241), and the registry tests (EntityDataSourceRegistryTests.cs:217,:220, including a deliberate duplicate-configuration pair at:228and:231).
EntityTypeConfigurationSQLServer<TEntity, TIdentifierType>
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfigurationSQLServer.cs:17· Level 7 · class (public abstract)
- What it is: the SQL Server shim,
[UseDataSource(DataSource.SQLServer)]over the engine-aware base (EntityTypeConfigurationSQLServer.cs:16-20). It is the type nearly every entity configuration in this workspace actually derives from, which makes it the practical entry point into everything the family does. - Depends on:
EntityTypeConfiguration<TEntity, TIdentifierType>(base,EntityTypeConfigurationSQLServer.cs:18);UseDataSourceAttributeandDataSource(:1,:16);AuditableBaseEntity<TIdentifierType>(:19). - Concept reinforced, and what a consumer inherits by writing one base name. Deriving from this class buys four behaviors without a line of code: the
DomainEventsexclusion fromEntityTypeConfigurationBase<TEntity, TIdentifierType>, a table named after the entity in a schema named after the module (EntityTypeConfiguration.cs:75), a primary key with the right generation policy for the entity'sIdValueGeneratedAttribute(:67-71), and aDataSourceKeyinEntityDataSourceRegistrythat makes the entity routable throughIUnitOfWorkandDbContextFactory. Adding a class-levelUseDatabaseAttributeon top overrides only the logical database, leaving the engine alone (EntityDataSourceRegistry.cs:167-169).[Rubric §15, Best Practices & Code Quality]assesses how much a consumer must know to add an entity correctly; here it is one base class name. - Where it's used: 28 configurations across ADC's Conference, Engagement, and Identity modules (for example
MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:13andMMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Persistence/EntityConfiguration/LivePolls/LivePollConfiguration.cs:16), 12 across Store's Catalog, Sales, and Identity modules, MMCA.Helpdesk's two Tickets configurations (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Infrastructure/Persistence/EntityConfiguration/TicketConfiguration.cs,MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Infrastructure/Persistence/EntityConfiguration/TicketCommentConfiguration.cs), and the framework's own notification configurations,PushNotificationConfigurationandUserNotificationConfiguration. It is also the SQL Server half of the cross-engine portability test (CosmosConfigurationPortabilityTests.cs:116).
StronglyTypedIdModelConfiguration
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conventions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/StronglyTypedIdModelConfiguration.cs:21· Level 6 · class (public static)
- What it is: the single call that wires strongly typed identifiers (ADR-115) into EF Core's model, once per host.
Applywalks the host'sStronglyTypedIdRegistryand declares one pre-convention type mapping per identifier type it describes, so every property of that type, keys, cross-module scalar references, owned-type members and the properties of a framework table alike, maps to its wrapped primitive (StronglyTypedIdModelConfiguration.cs:7-12,:29-51). - Depends on: EF Core's
ModelConfigurationBuilder,StronglyTypedIdValueConverter<TSelf, TValue>and its comparer counterpart fromMMCA.Common.Infrastructure.Persistence.Conversions, andStronglyTypedIdRegistryfromMMCA.Common.Shared.Identifiers. - Concept introduced, pre-convention configuration versus a model-finalizing convention.
[Rubric §8, Data Architecture]assesses whether a cross-cutting mapping rule is applied at the point in the pipeline where it actually works, and[Rubric §1, SOLID]assesses whether the opt-in stays orthogonal to code that never adopts it. EF Core exposes two very different places to declare a type-wide rule:ConfigureConventions(pre-convention, runs before the provider's own conventions see the model) and a model-finalizingIModelFinalizingConventionlikeSoftDeleteUniqueIndexConvention(runs last). The class doc comment states why this one has to be the former (StronglyTypedIdModelConfiguration.cs:14-18): a converter attached at finalization arrives after the provider's value-generation conventions have already inspected the property, so a wrappedintkey would silently lose its IDENTITY strategy. Declaring the mapping here means the provider CLR type is known before any of that runs, and a wrapped key generates exactly as its primitive did. - Walkthrough
Apply(configurationBuilder, registry)(StronglyTypedIdModelConfiguration.cs:29) null-guards both arguments, then iteratesregistry.Describe(), which yields the(identifierType, valueType)pairs the host declared (:36).- For each pair it closes the two open generics reflectively:
StronglyTypedIdValueConverter<,>.MakeGenericType(identifierType, valueType)andStronglyTypedIdValueComparer<>.MakeGenericType(identifierType)(StronglyTypedIdModelConfiguration.cs:38-41), then callsconfigurationBuilder.Properties(identifierType).HaveConversion(converterType, comparerType)(:43-45), the pre-convention API that applies the conversion to every property of that CLR type across the whole model, not just one entity's. configuredcounts the identifiers actually wired and is returned (StronglyTypedIdModelConfiguration.cs:34,47,50), giving the caller a number to log or assert against rather than a barevoid.
- Why it's built this way: strongly typed identifiers sit on the same opt-in footing as smart enumerations (ADR-115): a wrapper is two lines, and adopting the whole feature is one DI call,
services.AddStronglyTypedIds(typeof(OrderId).Assembly). The EF half of that contract has to be equally uniform, one call fromApplicationDbContext.ConfigureConventions, which every engine context inherits, so SQL Server, PostgreSQL, SQLite and Cosmos all get the same mapping without an engine branch (StronglyTypedIdModelConfiguration.cs:10-12). Driving the mapping from the registry rather than from a hard-coded type list means a host that never wraps an identifier callsApplyover an empty registry and nothing changes. - Where it's used: called once from
ApplicationDbContext'sConfigureConventions(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs).
IRepositoryFactory
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/IRepositoryFactory.cs:11· Level 7 · interface (public)
- What it is: a two-method contract that builds a repository over a caller-supplied
DbContext(IRepositoryFactory.cs:11-34).Createreturns a read-writeIRepository<TEntity, TIdentifierType>,CreateReadOnlyreturns anIReadRepository<TEntity, TIdentifierType>, and the class doc records the one behavior an implementation is expected to fold in: conditional MiniProfiler wrapping (IRepositoryFactory.cs:7-10). - Depends on: EF Core's
DbContextas the single parameter of both methods (NuGet,IRepositoryFactory.cs:1,:20,:31);IRepository<TEntity, TIdentifierType>andIReadRepository<TEntity, TIdentifierType>as return types (:2,:19,:30);AuditableAggregateRootEntity<TIdentifierType>andAuditableBaseEntity<TIdentifierType>as the two entity constraints (:3,:21,:32). - Concept introduced, a factory for the argument DI cannot supply. Plain constructor injection can hand a repository a
DbContext, and the container does exactly that for the open-generic registrationTryAddScoped(typeof(IRepository<,>), typeof(EFRepository<,>))(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:130). That registration can only ever bind one context, because DI resolves by type. This framework does not have one context: it has one context instance perDataSourceKey, created and cached per scope byDbContextFactory, and which instance an entity belongs to is a runtime lookup throughIDataSourceService(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/UnitOfWork.cs:55-56). So the context stops being a dependency and becomes an argument, and an argument-taking creation step is a factory. This is the type-level reason the codebase forbids constructor-injectingIRepository<,>directly: that path silently binds whatever the container's single registration resolves, while everything routed throughIUnitOfWorkreaches this factory and gets the context its entity actually lives in.[Rubric §2, Design Patterns]assesses whether a pattern earns its place rather than decorating the code; here the factory exists because DI provably cannot express the requirement.[Rubric §8, Data Architecture]assesses how deliberately storage boundaries are drawn; per-source repository construction is what keeps database-per-service (ADR-006) true at the level a handler touches. - Walkthrough
Create<TEntity, TIdentifierType>(DbContext dbContext)(IRepositoryFactory.cs:19-22): constrained toTEntity : AuditableAggregateRootEntity<TIdentifierType>andTIdentifierType : notnull. Writes go through aggregate roots only, which is the DDD rule expressed in the signature rather than in a comment.CreateReadOnly<TEntity, TIdentifierType>(DbContext dbContext)(IRepositoryFactory.cs:30-33): the same shape with a looser entity constraint,AuditableBaseEntity<TIdentifierType>. Reads may target a child entity that is not itself an aggregate root, which is exactly the asymmetryIUnitOfWorkexposes on its ownGetRepository/GetReadRepositorypair (UnitOfWork.cs:48-50,:53-55).- What the interface deliberately does not say: nothing about profiling, decoration, caching, or activation. Those are implementation choices, and
RepositoryFactorymakes them all.
- Why it's built this way: extracting the two lines from
UnitOfWorkinto a contract means the unit of work never asks "is profiling on"; it asks for a repository and gets whichever composition the host configured. It also gives the test suite a substitution point that does not require a real context factory. - Where it's used: registered scoped as
IRepositoryFactory -> RepositoryFactory(DependencyInjection.cs:131) and pinned by theIRepositoryFactoryrow of theAddInfrastructure_RegistersTheServicetheory, which asserts the scoped lifetime (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/DependencyInjectionInfrastructureTests.cs:74,:78-92). Its only production consumer isUnitOfWork, which injects it (UnitOfWork.cs:13,:16) and callsCreate(:42) andCreateReadOnly(:62) once per entity type, caching the result for the rest of the scope (:38-44,:58-64).
CrossDataSourceDegradeConvention
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conventions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/CrossDataSourceDegradeConvention.cs:34· Level 11 · class (public sealed)
- What it is: the model-finalizing convention that makes database-per-service work without forcing every module to write two versions of its entity configuration. It finds relationships whose two ends resolve to different physical databases and degrades them: the foreign key goes away, the navigation members are ignored, and entity types belonging to another database are removed from this model entirely (
CrossDataSourceDegradeConvention.cs:10-34). - Depends on:
DataSourceKey(the context's own physical source) andIEntityDataSourceRegistry(the entity-to-database map), both primary-constructor parameters (CrossDataSourceDegradeConvention.cs:34-36);DataSourceEnginesand theIsRelationalflag ofDataSourceEngineCapabilities, read to decide whether a compensating index is allowed (CrossDataSourceDegradeConvention.cs:66,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/DataSourceEngines.cs:40); EF Core'sIModelFinalizingConventionplus the mutable metadata surface (IMutableModel,IMutableEntityType,IMutableForeignKey,IMutableProperty). - Concept introduced, degrading a relationship instead of forbidding it.
[Rubric §7, Microservices Readiness]assesses whether a module can be lifted into its own service without rewriting application code, and[Rubric §8, Data Architecture]assesses whether ownership boundaries in the data model are real. Under database-per-service (ADR-006) an order row and a user row can live in different databases, and no database engine can enforce a foreign key across that line. The naive answers are both bad: forbid the navigation in the domain model (which distorts the domain to fit deployment), or keep the FK and hope the two entities always end up co-located (which breaks the moment they do not). This convention takes a third route. The configuration body is written once, as if everything were in one database, and the model builder subtracts what the current physical source cannot support. Three things are given up and each has a compensating mechanism: the FK constraint is replaced by an index over the surviving scalar columns, in-database navigation is replaced by theINavigationPopulatorbatch-loading path (ADR-002), and referential consistency is maintained by integration events rather than by the engine (CrossDataSourceDegradeConvention.cs:13-22). The payoff is stated at:26-30: when every entity resolves to the same source, nothing is foreign and the convention is a structural no-op, so the monolith model is identical to the single-database model. - Walkthrough
ProcessModelFinalizingopens by casting the convention model builder's metadata toIMutableModel(CrossDataSourceDegradeConvention.cs:45-47). The class doc behind the cast is load-bearing: cross-cutting helpers (soft-delete filters, concurrency tokens) have already promoted every entity type to theExplicitconfiguration source, and convention-sourced builder calls cannot overrideExplicit, so the mutable API is the only surface that can apply these changes (:23-25).IsForeign(CrossDataSourceDegradeConvention.cs:92-95) is the whole routing decision: look the CLR type's full name up in the registry, and call it foreign when the registry knows it and its key differs from this context's key. An unregistered type is never foreign.- The foreign set is computed over non-owned entity types, and when it is empty the method returns at once (
CrossDataSourceDegradeConvention.cs:49-56). That early return is the monolith fast path. - Step 1, degrade the FKs (
CrossDataSourceDegradeConvention.cs:63-75): for each local entity, every declared foreign key whose principal is foreign is passed toDegradeForeignKey. FKs declared on foreign dependents are not touched here because step 3 removes those entity types wholesale. Note thataddCompensatingIndexis computed once, as the context engine'sIsRelationalcapability (DataSourceEngines.For(contextKey.Engine).Capabilities.IsRelational,:66), not as a comparison against one named engine. DegradeForeignKey(CrossDataSourceDegradeConvention.cs:108-139) captures the non-shadow FK properties, removes the FK (which takes both navigations with it), and returns early when no compensating index is wanted or no scalar column survives (:119-122). The subtle part is:124-131: EF's ownForeignKeyIndexConventioncreated an index for the FK, and its removal is processed by a deferred event that would fire after the coverage check below, silently leaving the column unindexed. So the convention drops that convention-sourced index eagerly itself, then checks coverage and adds a plain index only if nothing already covers the columns (:133-138).HasCoveringIndex(CrossDataSourceDegradeConvention.cs:141-145) treats an index as covering when the FK columns are a prefix of its column list, in order, which is exactly the condition under which a composite index can serve a lookup on those columns.- Step 2, ignore the foreign members (
CrossDataSourceDegradeConvention.cs:80-83, implementation at:152-166): skip navigations pointing at foreign entities are removed, then every CLR property whose type (or collection element type) is foreign is added to the ignore list. The comment at:77-79explains why the second half is needed: removing a navigation leaves an unmapped CLR property of entity type behind, and EF's model validation rejects that. UnwrapCollectionElementType(CrossDataSourceDegradeConvention.cs:172-175) is the one-argument-generic unwrap that makesICollection<ForeignEntity>detectable as a collection of foreign entities.- Step 3, remove the foreign entity types (
CrossDataSourceDegradeConvention.cs:85-89). EF's relationship discovery pulls foreign types into the model as a side effect; this is where they leave it.
- Why it's built this way: the carve-out on the compensating index is spelled out at
CrossDataSourceDegradeConvention.cs:101-106. Cosmos, the one non-relational engine (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/DataSourceEngineCapabilities.cs:14-19), auto-indexes every property and rejects explicit index definitions, so adding a compensating index would fail model validation, and skipping it is what keeps a configuration body carrying a cross-source relationship portable to Cosmos without edits (ADR-018). Reading theIsRelationalcapability rather than testing forDataSource.CosmosDBputs this decision on the same single flag thatSoftDeleteUniqueIndexConventionandRestrictDeleteByDefaultConventionconsult for their own engine guard, so the three conventions cannot disagree about which engines support indexes and constraints. Doing all of this at model finalizing rather than at configuration time is what lets the same entity configuration serve the monolith and the extracted-service topology (ADR-008) with no per-topology branching in module code. - Where it's used: registered by
ApplicationDbContextinConfigureConventionswith the context'sDataSourceKeyand the resolvedIEntityDataSourceRegistry(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:610-614), first of the three finalizing conventions, ahead ofSoftDeleteUniqueIndexConvention(:392) andRestrictDeleteByDefaultConvention(:399). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/CrossDataSourceDegradeConventionTests.cs.
RestrictDeleteByDefaultConvention
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conventions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/RestrictDeleteByDefaultConvention.cs:42· Level 11 · class (public sealed)
- What it is: a model-finalizing convention that stamps every foreign key in the model with the source of its delete behavior, and restricts the ones nobody configured. It walks every declared foreign key once and defaults an unconfigured or convention-sourced cascade to
DeleteBehavior.Restrict, unless the foreign key belongs to an owned-type relationship, whose cascade EF itself owns (RestrictDeleteByDefaultConvention.cs:42-108). - Depends on: EF Core's
IModelFinalizingConvention,IConventionModelBuilder,IConventionForeignKey,ConfigurationSourceandDeleteBehavior;DataSource(its one primary-constructor parameter,RestrictDeleteByDefaultConvention.cs:42); andDataSourceEngineswith theIsRelationalflag ofDataSourceEngineCapabilitiesfor its engine guard (:66). - Concept introduced, defaulting to the safe cascade instead of the convenient one.
[Rubric §8, Data Architecture]assesses whether the storage design prevents the failure modes its own conventions could otherwise create, and[Rubric §15, Best Practices and Code Quality]assesses whether a default is a deliberate choice rather than whatever the underlying framework happens to ship. EF Core's own convention cascades a required foreign key by default, which means a relationship nobody explicitly configured silently deletes dependents when the principal is deleted, below the aggregate's invariants, the soft-delete filter and the domain events (RestrictDeleteByDefaultConvention.cs:14-21). This convention overrides that default: an unconfigured or convention-sourced delete behavior becomesRestrict, so a delete that would fan out across rows the domain never asked to remove fails loudly at the database instead of succeeding silently, and a genuine cascade becomes an.OnDelete(DeleteBehavior.Cascade)written in the entity configuration. - Walkthrough
DeleteBehaviorSourceAnnotation,ExplicitSource,ConventionSourceandOwnershipSource(RestrictDeleteByDefaultConvention.cs:44-57) are the four public constants: the annotation name the convention stamps on every foreign key (MMCA:DeleteBehaviorSource,:48), and the three values it can carry, recording whether the behavior came from an explicit configuration call, from this convention, or from EF's ownership handling.ProcessModelFinalizing(RestrictDeleteByDefaultConvention.cs:60-81) null-guards the model builder, returns immediately when the engine is not relational (!DataSourceEngines.For(engine).Capabilities.IsRelational,:66-69, the same capability checkSoftDeleteUniqueIndexConventionandCrossDataSourceDegradeConventionmake), then materializes every declared foreign key across the model into a list before applying anything (:71-75). The class doc gives the non-relational reason: Cosmos has no foreign-key constraints to restrict, and stamping a delete-behavior decision on a model that cannot enforce one would only make the audit lie (:35-39). The comment above the materialization names why it is a list: the cross-source convention runs first and may already have removed relationships, so nothing here should observe a collection mid-mutation.Apply(RestrictDeleteByDefaultConvention.cs:88-107) is the per-foreign-key decision. An ownership foreign key is stampedOwnershipSourceand left untouched (:90-94): EF owns that cascade, and overriding it would fight the owned-type feature. Otherwise the foreign key's existing delete-behaviorConfigurationSourceis read;null(nobody ever set one) orConfigurationSource.Convention(EF's own required-FK rule produced the cascading default) are both treated as "inherited, and ours to replace": the behavior is set toDeleteBehavior.Restrictand stampedConventionSource(:96-104). Anything else, meaning a configuration explicitly set a delete behavior, is stampedExplicitSourceand left exactly as configured (:106).
- Why it's built this way: the annotation is not cosmetic. Stamping the source of every delete behavior, rather than just flipping the ones that need it, gives a fitness test a byte-for-byte answer to "did this foreign key's cascade come from an explicit choice, from this convention, or from ownership", read straight off a finalized model without re-running the convention (
RestrictDeleteByDefaultConvention.cs:29-34). That is what ADR-119 records as the decision: default every unconfigured relationship toRestrictrather than to EF's own cascading default, and make the source of that decision inspectable rather than implicit. Running at model finalizing, after every module'sIEntityTypeConfigurationhas declared its own relationships, is what lets the convention see the whole model without needing to know which modules exist, the same timingSoftDeleteUniqueIndexConventionuses for the same reason. - Where it's used: registered by
ApplicationDbContextinConfigureConventionswith the context's own engine (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:627), last of the three finalizing conventions so it never stamps a relationship the cross-source convention has already removed (ApplicationDbContext.cs:622-626). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conventions/RestrictDeleteByDefaultConventionTests.csand byMMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Domain/DeleteBehaviorConventionTests.cs, which subclasses the sharedDeleteBehaviorConventionTestsBaseand theArchitectureRules.DeleteBehaviorrule group so ADC's own model is checked against the same contract.
SoftDeleteUniqueIndexConvention
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Conventions·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/SoftDeleteUniqueIndexConvention.cs:34· Level 11 · class (public sealed)
- What it is: an EF Core model-finalizing convention that puts the
IsDeleted = 0predicate on every unique index of every soft-deletable entity type in the model, so a soft-deleted row stops occupying its unique slot (SoftDeleteUniqueIndexConvention.cs:11-34). - Depends on: EF Core's
IModelFinalizingConvention,IConventionModelBuilderandIConventionEntityType;SoftDeleteFilterSqlfor the predicate text; theDataSourceengine enum, taken as its one primary-constructor parameter (SoftDeleteUniqueIndexConvention.cs:34);DataSourceEngineswith theIsRelationalflag ofDataSourceEngineCapabilitiesfor its engine guard (:43); andIAuditableEntityas the marker for "this entity is soft-deletable". - Concept introduced, the model-finalizing convention as a cross-cutting model rule.
[Rubric §6, CQRS & Event-Driven Design]assesses whether policies that apply to every entity are expressed once rather than repeated per configuration, and[Rubric §8, Data Architecture]assesses whether the data model's invariants actually hold. EF exposes convention hooks that run while the model is being built;IModelFinalizingConventionis the last of them, which means it observes the model after every module'sIEntityTypeConfigurationhas declared its indexes. That timing is what makes a blanket rule possible: the convention does not need to know which modules exist or what they declared, it just walks the finished model. The bug it closes is a genuine soft-delete trap, stated in the doc comment (SoftDeleteUniqueIndexConvention.cs:12-17): soft-delete a speaker, and the unique index on email still blocks creating a new speaker with that email, because the row is invisible to the application but entirely visible to the database's uniqueness check. Adding the filter aligns what the database enforces with what the application shows. - Walkthrough
ProcessModelFinalizing(SoftDeleteUniqueIndexConvention.cs:37-51) null-guards the model builder, then returns immediately when the engine is not relational (!DataSourceEngines.For(engine).Capabilities.IsRelational,:43-44). The class doc names the coverage: SQL Server, PostgreSQL and SQLite all support partial or filtered indexes, and the convention is a no-op for Cosmos (:28-31).- The entity selection is two predicates (
SoftDeleteUniqueIndexConvention.cs:46-47): the CLR type must be assignable toIAuditableEntity, and the entity type must not be owned. Owned types share their owner's table and have no independent index story, so they are excluded. ApplyFilterToUniqueIndexes(SoftDeleteUniqueIndexConvention.cs:53-82) asksSoftDeleteFilterSqlto build the predicate for this engine (:57,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SoftDeleteFilterSql.cs:35) and bails when it isnull(:58-59), then walks the entity's indexes, skipping every non-unique one (:63-64). The predicate text is engine-specific:[IsDeleted] = 0on SQL Server,"IsDeleted" = 0on SQLite,"IsDeleted" = falseon PostgreSQL, whose flag is a real boolean (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:117,SqliteDataSourceEngine.cs:115,PostgreSQLDataSourceEngine.cs:116).- For a unique index the convention branches three ways on the existing filter. No filter at all: set the soft-delete predicate (
SoftDeleteUniqueIndexConvention.cs:67-71). A filter that already constrains the soft-delete column, whether a hand-authored literal or the output ofHasSoftDeleteFilter: leave it exactly as it is, detected bySoftDeleteFilterSql.ContainsPredicate(:73-76, the helper atSoftDeleteFilterSql.cs:53). Anything else: append the clause as{existingFilter} AND {filterSql}(:80). - That append is the load-bearing part, and the doc comment explains why it replaced the earlier "skip an index that already has a filter" behavior (
SoftDeleteUniqueIndexConvention.cs:18-27). Skipping meant the exact partial-unique indexes a model bothered to hand-author (for example one narrowed on[DedupKey] IS NOT NULL) were the only ones a soft-deleted row could keep blocking. TheContainsPredicatecheck is what keeps appending idempotent: without it, a second model build would produce... AND [IsDeleted] = 0 AND [IsDeleted] = 0.
- Why it's built this way: the comment at
SoftDeleteUniqueIndexConvention.cs:55-56names the reason the predicate comes fromSoftDeleteFilterSqlrather than from a local string: it is the same builder the opt-in extension reaches, so the automatic path and the hand-authored path can never disagree about column name or identifier quoting, and theANDordering at:78-79is chosen to matchHasSoftDeleteFilter(additionalFilter:)byte for byte. Restricting the automatic behavior to unique indexes is a deliberate blast-radius choice: a unique index without the filter is a correctness bug under soft delete, while a non-unique index without it is only a performance question, and performance questions belong to whoever wrote the index. Guarding on theIsRelationalcapability rather than onDataSource.CosmosDBkeeps this convention aligned withCrossDataSourceDegradeConventionandRestrictDeleteByDefaultConventionon which engines have indexes at all. The whole decision, including the 2026-08-26 revision from skipping to appending, is ADR-095; soft delete as a policy is ADR-005; covering SQL Server, PostgreSQL and SQLite while skipping Cosmos is the engine-portability posture of ADR-018. - Where it's used: registered by
ApplicationDbContextinConfigureConventionswith the context's own engine (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:620), immediately afterCrossDataSourceDegradeConventionand beforeRestrictDeleteByDefaultConvention. The comment there records the ordering intent and the precedence rule: it runs at finalization, after module configurations have declared their indexes, and hand-authored index filters are respected (ApplicationDbContext.cs:616-618).UserNotificationConfigurationrelies on it outright for its unique index, declaring no filter of its own. Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conventions/SoftDeleteUniqueIndexConventionTests.cs.
NavigationPopulatorStartupValidator
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Navigation·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:36· Level 11 · class (internal sealed)
- What it is: an
IHostedServicethat fails the host at start when a navigation EF Core cannot include has no populator to load it, instead of letting every read with includes return that navigation empty (NavigationPopulatorStartupValidator.cs:11-13,:36-40). A navigation is unsupported when its two entities live in different databases, when the engine has no relational includes (Cosmos DB), or when the target entity is not mapped in this host at all (:15-17). - Depends on: four primary-constructor parameters (
NavigationPopulatorStartupValidator.cs:36-40):IEntityConfigurationAssemblyProvider(the configuration assemblies to scan),IEntityDataSourceRegistry(which entities this host maps),IDataSourceService(whether two entities support an include between them) andIServiceScopeFactory(the scope populators are resolved in). It reusesNavigationMetadataProviderand itsNavigationMetadataresult (:42-43,:71,:127), asksINavigationPopulator<in TEntity>registrations throughINavigationPopulatorCoverage(:88-89,:111), reportsNavigationPropertyInfoentries (:93), and enumerates mapped entities through the internalEntityDataSourceRegistry.EnumerateEntityConfigurations(:116, declared atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/EntityDataSourceRegistry.cs:181). - Concept introduced, turning a silent empty read into a start-up failure.
[Rubric §8, Data Architecture]assesses whether database-per-service boundaries are enforced rather than assumed, and[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether misconfiguration surfaces early rather than as wrong data.CrossDataSourceDegradeConventionremoves a cross-database navigation from the EF model, so anIncludeover it has nothing to load; the compensating mechanism is the entity's populator (ADR-002). Application registration defaults every entity to the open-genericNullNavigationPopulator<TEntity>(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:53-58), which loads nothing. Without this check, forgetting the closed registration for one entity would compile, start and return empty collections. The validator closes that gap by classifying every navigation exactly as the query path does and refusing to start while any unsupported one is uncovered. - Walkthrough
StartAsync(NavigationPopulatorStartupValidator.cs:46-59): awaitsFindUncoveredNavigationsAsyncand, when the list is non-empty, throwsInvalidOperationExceptionnaming every uncovered navigation and the fix: register aDeclarativeNavigationPopulator<TEntity>with one descriptor per navigation (:51-57).StopAsyncis a no-op (:62).FindUncoveredNavigationsAsync(NavigationPopulatorStartupValidator.cs:69-106,internalso tests call it directly): builds oneNavigationMetadataProviderover the data-source service (:71), then for each mapped entity type collects its unsupported navigations and skips entities with none (:77-83). The async scope is created lazily on the first entity that needs one (:85-87), so a host with no unsupported navigation resolves nothing, and it is disposed in afinally(:96-102). Each uncovered entry is formatted{Entity}.{Navigation} -> {TargetEntity}with full type names (:91-93) and the list is sorted ordinally for a stable message (:104).IsHandled(NavigationPopulatorStartupValidator.cs:108-113): no registered populator means not handled; a populator that implementsINavigationPopulatorCoverageanswers throughHandles(navigation); any other populator is trusted. The class doc spells out the three outcomes: theNullNavigationPopulatordefault handles nothing, a declarative populator handles what its descriptors name, and a hand-written populator that declares no coverage is trusted (:20-23).MappedEntityTypes(NavigationPopulatorStartupValidator.cs:115-119): every distinct entity type with an entity configuration in the scanned assemblies, kept only when the registry knows its full name (registry.TryGetDataSourceKey,EntityDataSourceRegistry.cs:50).UnsupportedNavigations(NavigationPopulatorStartupValidator.cs:123-132): closesNavigationMetadataProvider.BuildIncludesover the entity type through the cachedMethodInfo(:42-43), invokes it with both include kinds enabled ([true, true],:129) and returnsUnsupportedIncludes(:131). The comment at:121-122states the point: the check uses the provider the query path itself uses, so it and a real read cannot classify a navigation differently.
- Why it's built this way: the check has to cost nothing on the common topology. A host whose navigations all share one relational database has nothing unsupported, so it resolves no populator and pays one reflection pass (
NavigationPopulatorStartupValidator.cs:25-28). Reusing the query path's classifier rather than re-deriving "is this cross-database" keeps the validator from drifting away from what reads actually do. Trusting a hand-written populator that does not declare coverage avoids false failures for existing populators, at the cost of not checking them. - Where it's used: registered by
AddInfrastructureas a singletonIHostedServicethroughTryAddEnumerable, so several modules callingAddInfrastructurestill run the check once (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:265-270). Covered byMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Navigation/NavigationPopulatorStartupValidatorTests.cs: same-database navigations pass with the null default and resolve no populator (:39), cross-database navigations on the default are reported (:48), an unmapped target is reported (:58), a declarative populator covers only its named navigations (:74), a hand-written populator without coverage is trusted (:92), no registration at all reports everything (:106),StartAsyncfails naming entity and navigation (:114) and completes when everything is includable (:126), andAddInfrastructureregisters exactly one hosted service (:140).
PushNotificationConfiguration
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration.Notifications·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/PushNotificationConfiguration.cs:16· Level 11 · class (internal sealed)
- What it is: the EF Core mapping for
PushNotification, the framework's own broadcast-notification aggregate (PushNotificationConfiguration.cs:16-85). It is one of only two entity configurations that ship inside the framework rather than in a consumer application, and it is where the dedup guarantee behind a retried send is actually enforced. - Depends on:
EntityTypeConfigurationSQLServer<TEntity, TIdentifierType>as its base (PushNotificationConfiguration.cs:17), including the inheritedEffectiveEngineproperty (:82-83, declared atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfiguration.cs:61);PushNotificationand itsDedupKeyMaxLength/ScopeKeyMaxLength/NativeDeliveryUnitMaxLengthconstants (:3,:47,:53,:63, declared atMMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotification.cs:18,:22,:25);PushNotificationInvariantsfor the title and body lengths (:4,:29,:33);PushNotificationStatusindirectly through the string conversion (:43);UseDatabaseAttribute(:15); theHasSoftDeleteFiltermember fromIndexBuilderExtensions(:81);QuoteColumnfromSoftDeleteFilterSql(:83,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/SoftDeleteFilterSql.cs:70-71); EF Core'sEntityTypeBuilder<TEntity>(NuGet,:1-2). - Concept introduced, a framework-owned entity that has to name its own home. Every other configuration in this workspace lets convention pick the schema and the logical database: a SQL Server entity is mapped by its engine to a table in a schema named by
NamespaceConventions, which is the namespace segment immediately precedingDomain(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/Engines/SQLServerDataSourceEngine.cs:101). That rule is right for a consumer entity inMMCA.ADC.Conference.Domain.Sessions(schemaConference) and wrong here, because this entity lives inMMCA.Common.Domain.Notifications.PushNotifications, whose preceding segment isCommon. The configuration therefore states both facts explicitly:[UseDatabase("Notification")](PushNotificationConfiguration.cs:15) fixes the logical database thatEntityDataSourceRegistryrecords, andToTable(nameof(PushNotification), "Notification")(:25) overrides the auto-derived schema after the base call. The class doc states this reasoning in place (:8-14), including the consequence that matters for a small host: a host with noDataSources:Notificationentry keeps these tables in its default database.[Rubric §8, Data Architecture]assesses whether the physical layout is a decision rather than an accident; this is a convention override made visible in two attributes on one class.[Rubric §29, Resilience, Reliability & Business Continuity]assesses whether shared capabilities carry their own infrastructure; the notification feature ships its schema with the framework instead of asking each consumer to re-declare it. - Concept introduced, letting the database arbitrate a duplicate send. A "have I already sent this?" check in a handler is a check-then-act race: two retries of the same request can both read "no row" before either writes. The filtered unique index on
DedupKey(PushNotificationConfiguration.cs:79-83) removes the race by moving arbitration into the engine, and the filter is what makes it usable:IS NOT NULLkeeps the many sends that carry no key from colliding with each other (SQL Server treats NULLs as equal in a unique index), andIsDeleted = 0keeps a soft-deleted notification from squatting on its key forever. The comment block records both halves, the defect that produced the second one, and why the filter is written for the engine of the model being built (:65-78).[Rubric §12, Performance & Scalability]assesses whether index choices are reasoned; the file argues for one index and against another in the same class.[Rubric §29, Resilience & Business Continuity]assesses behavior under retry; at-least-once delivery upstream is only safe because this index makes a repeated send idempotent at the storage layer. - Walkthrough
base.Configure(builder)(PushNotificationConfiguration.cs:22): runs the inherited chain first.EntityTypeConfigurationBase<TEntity, TIdentifierType>ignores the aggregate's in-memoryDomainEventscollection (EntityTypeConfigurationBase.cs:29-32), thenEntityTypeConfiguration<TEntity, TIdentifierType>reads the declared engine off the[UseDataSource(DataSource.SQLServer)]carried by the shim base (EntityTypeConfiguration.cs:43-46,EntityTypeConfigurationSQLServer.cs:16), recordsEffectiveEngineas the engine annotated on the model being built, falling back to the declared one (EntityTypeConfiguration.cs:48-49), and hands the declared engine to its engine'sApplyKeyAndTableMapping(:51,:68-77). For SQL Server that is table plus schema,HasKey(p => p.Id), andValueGeneratedOnAdd()because the entity carriesIdValueGeneratedAttribute(SQLServerDataSourceEngine.cs:94-104,PushNotification.cs:14).- The schema override (
PushNotificationConfiguration.cs:25):ToTable(nameof(PushNotification), "Notification"), applied after the base call so it replaces the derivedCommonschema rather than being replaced by it. Ordering is load-bearing here. - Required scalars (
:27-39):Titlerequired withHasMaxLength(PushNotificationInvariants.TitleMaxLength)(200,MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/Invariants/PushNotificationInvariants.cs:13),Bodyrequired atBodyMaxLength(2000,PushNotificationInvariants.cs:16),SentByUserIdandRecipientCountrequired. The column widths are the same constants the domain validates against (PushNotificationInvariants.cs:18-26), so the database cannot be narrower than the invariant. Statusstored as text (:41-44):HasConversion<string>()withHasMaxLength(20). The CLR type is thePushNotificationStatusenum with three members,Pending,Sent,Failed(MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/PushNotifications/PushNotificationStatus.cs:6-16); persisting the name rather than the ordinal means reordering or inserting an enum member does not silently re-interpret existing rows.DedupKey(:46-47): nullable, bounded byPushNotification.DedupKeyMaxLength(128,PushNotification.cs:18). The domain records that this is typically theIdempotency-Keyheader value and that the filtered unique index is what arbitrates the race (PushNotification.cs:41-47).ScopeKey(:52-53): nullable, bounded byScopeKeyMaxLength(128,PushNotification.cs:21), and deliberately not indexed. The comment gives the economics (:49-51): the scope filter runs after the primary-key join fromUserNotification, over a table holding one row per send, so an index would cost writes without buying a read.- The native push outcome columns (
:55-63):AndroidSent,AndroidFailed,AppleSentandAppleFailedare mapped as plain properties (:58-61) over the domain'sint?members (PushNotification.cs:62-71), so each is a nullable integer column; null means that platform was not attempted, or the row was written before the outcome was recorded (:55-56).NativeDeliveryUnitnames the provider's delivery unit the counts are in and is a nullable string bounded byPushNotification.NativeDeliveryUnitMaxLength(20,:62-63,PushNotification.cs:24,:79). The values are written byRecordNativePushOutcome, which leaves the overallStatusas the SignalR leg's (PushNotification.cs:169-186). There are no engine-specific calls here: the comment records that one mapping serves every engine because a PostgreSQL or SQLite host applies this configuration to its own model (:56-57). - The filtered unique index (
:79-83):HasIndex(p => p.DedupKey).IsUnique().HasSoftDeleteFilter(EffectiveEngine, additionalFilter: ...), where the additional filter is theDedupKeycolumn quoted forEffectiveEnginebySoftDeleteFilterSql.QuoteColumnfollowed byIS NOT NULL(:83). The helper composes the final predicate as{additionalFilter} AND {softDeletePredicate}(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/IndexBuilderExtensions.cs:62-65), and the soft-delete half comes fromSoftDeleteFilterSql, which reads the actual column name out of the model and builds the predicate for the given engine (SoftDeleteFilterSql.cs:35). The comment at:68-71gives the reason the engine is passed explicitly rather than left to the helper'sDataSource.SQLServerdefault (IndexBuilderExtensions.cs:53): a host that configures only PostgreSQL or SQLite substitutes its engine and applies this SQL Server configuration to that model, and the Cosmos context strips relational indexes. On a SQL Server model the result is[DedupKey] IS NOT NULL AND [IsDeleted] = 0, asserted verbatim byDedupKeyIndex_FiltersOutSoftDeletedRows(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/PushNotificationConfigurationTests.cs:27-31) and byOnASqlServerHost_NotificationIndexFilters_KeepTheBracketedForm(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/NotificationConfigurationEngineTests.cs:68); on a PostgreSQL-only host it is"DedupKey" IS NOT NULL AND "IsDeleted" = false(NotificationConfigurationEngineTests.cs:46). - Why the opt-in call is belt and braces, not a requirement (
:73-78):SoftDeleteUniqueIndexConventionstamps the soft-delete predicate onto every unique index of a soft-deletable entity, and it extends a hand-authored filter instead of skipping it: an index that already declares a predicate gets{existingFilter} AND {filterSql}in that exact order (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/SoftDeleteUniqueIndexConvention.cs:67-80), and an index whose filter already constrains the soft-delete column is left untouched so a second model build cannot append the clause twice (:73-76). BecauseHasSoftDeleteFilterproduces the same SQL in the same order from the same column name, the convention recognizes this index and stops, which is what the configuration's own comment says (PushNotificationConfiguration.cs:76-78).
- Why it's built this way: the two overrides exist because a framework-owned domain type cannot be named by the convention that names consumer domain types, and stating the target explicitly is cheaper than special-casing the convention. Writing the filter for
EffectiveEnginerather than as a bracketed literal is what lets one SQL Server-declared configuration serve a PostgreSQL or SQLite host: the test that pins it states the failure it prevents, a bracketed SQL Server literal being a syntax error on Npgsql (NotificationConfigurationEngineTests.cs:14-17). The soft-delete clause on the dedup index is a fix, not an original design: it closes a defect where a soft-deleted notification held its dedup key permanently, and ADC's migration for it is an explicit expand-contract drop and recreate, since a filtered index predicate cannot be altered in place (MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Notification/Migrations/20260804185520_CommonV1141PushNotificationDedupIndexSoftDeleteFilter.cs:13-31). The migration comment argues the safety case explicitly: the new predicate is strictly more permissive, so a previous revision running against the new index still succeeds. - Where it's used: discovered by assembly scan rather than by a direct reference.
AddNotificationInfrastructure()registers this class's assembly as an entity-configuration source (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:25-30, naming the type only to get itsAssemblyat:29), and the only production caller is ADC's Notification module (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:33), whose service points the logicalNotificationsource at theADC_Notificationdatabase (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/appsettings.Development.json:37-41). Store hosts no notification entities today: the only other callers ofAddNotificationInfrastructureare Common's own DI tests. Behavior is pinned against a real model built from this exact configuration (PushNotificationConfigurationTests.cs:104-110): index uniqueness (:23-25), the composed filter (:27-31), the scope-key length and nullability (:36-42), the deliberate absence of a scope-key index (:44-50), the four native push counts as nullableintcolumns (:54-66), andNativeDeliveryUnitas a nullable string bounded at 20 (:68-77). The engine substitution is pinned separately byNotificationConfigurationEngineTests, which builds the full context over a PostgreSQL-only and a SQL ServerNotificationsource (NotificationConfigurationEngineTests.cs:27-47,:49-69). - Caveats / not-in-source: the
PushNotificationConfigurationTestsdouble builds the model on SQLite (PushNotificationConfigurationTests.cs:97-99) through a plainDbContextthat carries no engine annotation, soEffectiveEnginefalls back to the declared SQL Server engine (EntityTypeConfiguration.cs:48-49) and the asserted filter is the bracketed SQL Server form; the engine-substituted output is only asserted byNotificationConfigurationEngineTests.
RepositoryFactory
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Repositories.Factory·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/Factory/RepositoryFactory.cs:15· Level 10 · class (public sealed)
- What it is: the single implementation of
IRepositoryFactory. It activates the concrete EF repository over the suppliedDbContextthrough a compiled, cached constructor delegate, and wraps it in a profiling decorator when the host has MiniProfiler switched on (RepositoryFactory.cs:15-86). - Depends on:
IServiceProviderandIOptions<ApplicationSettings>, both primary constructor parameters, unwrapped to fields at construction (RepositoryFactory.cs:15-18);ApplicationSettingsfor the one flag it reads (:6,:34,:58);EFRepository<TEntity, TIdentifierType>,EFReadRepository<TEntity, TIdentifierType>,EFRepositoryDecorator<TEntity, TIdentifierType>,EFReadRepositoryDecorator<TEntity, TIdentifierType>as the four concrete types it can build (:32,:37,:56,:61);Microsoft.Extensions.DependencyInjection.ActivatorUtilitiesand itsObjectFactorydelegate type (NuGet,:3,:81-85);System.Collections.Concurrent.ConcurrentDictionary(BCL,:1,:70); EF Core'sDbContext(:2). - Concept introduced, reflective activation traded for a cached compiled factory.
ActivatorUtilities.CreateInstanceis the usual way to build a type whose constructor mixes DI-resolved services with caller-supplied arguments, and it is what this class used to call. Its cost is per call: it matches the constructor by reflection every time and caches nothing, so a request touching four aggregates paid four reflective activations.ActivatorUtilities.CreateFactorydoes the matching once and returns anObjectFactory, a compiled delegate that can be invoked repeatedly. The insight that makes caching safe is stated in the code (RepositoryFactory.cs:74-79): each closed repository type here always takes the same argument shape, so the delegate can be keyed by type alone with no risk of a shape mismatch.[Rubric §12, Performance & Scalability]assesses whether hot paths avoid repeated per-call work; repository creation is on every command and query, so a per-type one-time cost replaces a per-call one.[Rubric §15, Best Practices & Code Quality]assesses whether an optimization is justified in place rather than left as folklore; the doc comment names the exact scenario it fixes. - Concept reinforced, decoration decided by configuration. The decorator pattern itself is taught in the CQRS pipeline chapter. Here it appears in its simplest form and with a switch:
ApplicationSettings.UseMiniProfiler(MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ApplicationSettings.cs:14) decides whether the plain repository is returned or is passed as the inner instance of a timing decorator. When the flag is off there is no wrapper object and no indirection at all, so profiling costs nothing in a production host that leaves it off.[Rubric §13, Observability & Operability]assesses whether the system can be inspected without being rebuilt; per-repository timing is a configuration flip. - Walkthrough
- Primary constructor (
RepositoryFactory.cs:15-18): captures the provider into_serviceProviderand, importantly, resolvesIOptions<ApplicationSettings>.Valueonce into_applicationSettingsrather than on every call. Nothing else is resolved at construction, so the class stays cheap to create per scope (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:131registers it scoped). Create<TEntity, TIdentifierType>(DbContext dbContext)(:26-42): buildsEFRepository<TEntity, TIdentifierType>throughFactory(..., DbContextArg)(_serviceProvider, [dbContext])(:31-32). Only the context is passed positionally; the repository's two remaining constructor parameters are optional,TimeProvider?andICurrentUserService?(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:27-31), and come from the provider, with the class doc recording the fallback when they are absent: the system clock and no user stamp (EFRepository.cs:20-26). WhenUseMiniProfileris true (:34) the instance is re-wrapped by activatingEFRepositoryDecorator<TEntity, TIdentifierType>with an argument shape of[typeof(IRepository<TEntity, TIdentifierType>)](:36-38), matching the decorator's singleinnerparameter (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepositoryDecorator.cs:14).CreateReadOnly<TEntity, TIdentifierType>(DbContext dbContext)(:50-66): the identical sequence againstEFReadRepositoryandEFReadRepositoryDecorator, with the looserAuditableBaseEntity<TIdentifierType>constraint.DbContextArg(:68): a single staticType[]holdingtypeof(DbContext), shared by both creation paths so the common case allocates no argument-type array per call.FactoryCache(:70): a staticConcurrentDictionary<Type, ObjectFactory>, so the compiled delegates are shared process-wide across scopes and requests, not per factory instance.Factory(Type implementationType, Type[] argumentTypes)(:81-85):FactoryCache.GetOrAdd(implementationType, static (type, args) => ActivatorUtilities.CreateFactory(type, args), argumentTypes). Two details are deliberate: the value factory isstatic, so it captures nothing, and the argument types travel throughGetOrAdd's state parameter instead of a closure, which is what keeps the lookup allocation-free on the hit path.
- Primary constructor (
- Why it's built this way:
UnitOfWorkmust create a repository over a specific context instance chosen by data source (UnitOfWork.cs:55-57), which no container registration can express, so something has to do the activation by hand. Once that step exists, it is also the natural place to fold in the optional profiling decorator, and the natural place to pay the reflection cost once rather than per call. The class ispublicwhile all four types it builds areinternal, which is the point: consumers get the contract and the composition, never the concrete repository types. - Where it's used: injected into
UnitOfWork(UnitOfWork.cs:13,:16) and called fromGetRepository(:42) andGetReadRepository(:62). Because the unit of work caches one repository per entity type per scope (:38-44), the factory typically runs once per entity type per request, and the compiled delegate is reused for every later request in the process. All four composition outcomes are pinned directly against a real SQLite context: plain repository with the flag off, decorated with it on, and the same pair for the read side (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Repositories/RepositoryFactoryTests.cs:45-95), plus two tests asserting the built instances are functional repositories (:95-115). Those tests construct the factory directly withOptions.Create(new ApplicationSettings { UseMiniProfiler = false })(:98,:100), which is the shape the primary constructor takes. - Caveats / not-in-source: the cache is keyed by implementation type only, which is correct exactly as long as every call site for a given closed type passes the same argument shape. Both current call sites do, and the doc comment states that assumption (
RepositoryFactory.cs:74-79), but nothing in the code enforces it: a future overload passing a differentargumentTypesarray for an already-cached type would silently reuse the first delegate.
UserNotificationConfiguration
MMCA.Common.Infrastructure ·
MMCA.Common.Infrastructure.Persistence.Configuration.EntityTypeConfiguration.Notifications·MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/Notifications/UserNotificationConfiguration.cs:15· Level 14 · class (internal sealed)
- What it is: the EF Core mapping for
UserNotification, the per-user inbox row that pairs a recipient with a broadcast (UserNotificationConfiguration.cs:15-47). It is the sibling ofPushNotificationConfigurationand shares its shape exactly:internal sealed,[UseDatabase("Notification")],EntityTypeConfigurationSQLServer<TEntity, TIdentifierType>base, and aToTablethat overrides the derivedCommonschema. - Depends on:
EntityTypeConfigurationSQLServer<TEntity, TIdentifierType>(UserNotificationConfiguration.cs:16), including the inheritedEffectiveEngineproperty (:45, declared atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/EntityTypeConfiguration/EntityTypeConfiguration.cs:61);UserNotification(:3,:24);UseDatabaseAttribute(:14); theHasSoftDeleteFiltermember fromIndexBuilderExtensions(:45);SoftDeleteUniqueIndexConvention, which supplies the filter on its unique index (:38-41); EF Core'sEntityTypeBuilder<TEntity>(NuGet,:1-2). - Concept reinforced: the schema-and-database override taught at
PushNotificationConfiguration, with the identical doc comment stating why (UserNotificationConfiguration.cs:7-13). What is worth studying here instead is the index pair, which shows the two routes a soft-delete filter takes onto an index side by side: the convention for the unique one, the opt-in helper for the non-unique one, neither written as an engine-specific literal.[Rubric §12, Performance & Scalability]assesses whether hot read paths are backed by an index that matches the query's predicate; the unread lookup below is a textbook covering-filter case. - Walkthrough
- Base call and schema override (
UserNotificationConfiguration.cs:21,:24): same order and same reason as its sibling. - Scalars (
:26-36):UserIdandPushNotificationIdrequired,IsReadrequired withHasDefaultValue(false)so an inserted row is unread at the database level too, andReadOnmapped with no facets, staying nullable because the domain declares itDateTime?(MMCA.Common/Source/Core/MMCA.Common.Domain/Notifications/UserNotifications/UserNotification.cs:24). - Uniqueness per recipient (
:38-41):HasIndex(p => new { p.UserId, p.PushNotificationId }).IsUnique(), one inbox row per user per notification among live rows, with no filter declared here. The comment states where the predicate comes from (:38-39):SoftDeleteUniqueIndexConventionsets the soft-delete filter on a unique index of a soft-deletable entity that has none (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/SoftDeleteUniqueIndexConvention.cs:67-71), built for the context's own engine (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:620), so the SQL comes out in the syntax of whichever engine the model is built for. - The unread lookup (
:43-45):HasIndex(p => new { p.UserId, p.IsRead }).HasSoftDeleteFilter(EffectiveEngine), non-unique, serving the per-user unread query behind the notification badge. This is the case the convention deliberately skips, since it continues past any index that is not unique (SoftDeleteUniqueIndexConvention.cs:63-64), so the explicit call is required to keep soft-deleted rows out of the index. PassingEffectiveEnginerather than relying on the helper'sDataSource.SQLServerdefault (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Configuration/IndexBuilderExtensions.cs:53) is what makes the filter[IsDeleted] = 0on a SQL Server model and"IsDeleted" = falseon a PostgreSQL-only host (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Configuration/NotificationConfigurationEngineTests.cs:67,:45). - No relationship to
PushNotification(:29-30):PushNotificationIdis configured as a plain required scalar, with noHasOneorWithManyanywhere in the file, and the domain entity exposes no navigation property either, only the identifier (UserNotification.cs:18). The inbox row references the broadcast by value.
- Base call and schema override (
- Why it's built this way: modeling the reference as a bare scalar keeps the entity honest about what the database enforces, and it is the shape the framework can move without rework. Both notification tables carry
[UseDatabase("Notification")]today, so they land in one database and a declared relationship would be legal; the moment a host routed them apart,CrossDataSourceDegradeConventionwould strip the EF relationship and the FK constraint anyway and leave exactly this scalar behind (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/CrossDataSourceDegradeConvention.cs:10-22). That is the same rule ADC applies to every cross-module reference under database-per-service (ADR-006). Leaving both index filters to engine-aware code rather than a bracketed literal is what lets this SQL Server-declared configuration be applied to a PostgreSQL or SQLite model, where the bracketed form is a syntax error on Npgsql (NotificationConfigurationEngineTests.cs:14-17). - Where it's used: registered by the same assembly scan as its sibling (
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:25-30) and reached in production only through ADC's Notification module (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:33), where theUserNotificationtable lands in theNotificationschema ofADC_Notification(MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/appsettings.Development.json:37-41). Its index filters are pinned byNotificationConfigurationEngineTests, which loads this configuration's assembly into a full context over a PostgreSQL-only and a SQL ServerNotificationsource (NotificationConfigurationEngineTests.cs:42,:64) and asserts both indexes carry the engine's soft-delete predicate (:45,:67, exactly two indexes at:73-74). - Caveats / not-in-source: that test pins only the two index filters; the scalar mapping (required columns, the
IsReaddefault) has no dedicated assertion in the Common suite and is exercised indirectly through the ADC Notification migrations and integration tier.