Shared : Infrastructure.Persistence
The Shared.Infrastructure.Persistence project provides the persistence layer abstractions and implementations built on top of Entity Framework Core. It includes base repository classes for command, query, and domain operations, a Unit of Work implementation, a domain event publishing interceptor, and dependency injection helpers for database context and service registration.
Abstractions : Repositories
- CommandRepository<TDbContext, TEntity, TEntityId> : An abstract base class for write-side repositories. It provides
Add,Update,Remove, andGetEntityAsyncmethods that operate on theDbContextdirectly. - QueryRepository<TDbContext> : An abstract base class for read-side repositories. It exposes an
IDbContextFactoryfor creating short-lived, isolated read contexts. - DomainRepository<TDbContext> : An abstract base class for domain-level data checks. It provides
ExistsWithPropertyNameAsyncandExistsWithPropertyNameExcludingIdAsyncmethods for uniqueness validation, using a context factory for each query.
Dependency Injection
InfrastructurePersistenceDependencyInjection static class provides helper methods to register persistence services into the DI container :
- AddDbContextFactory : Registers an
IDbContextFactoryfor a givenDbContexttype, configured with SQL Server and connection resiliency (retry on failure). Supports optional additional configuration via a callback. - AddDbContextFactoryWithDomainEvents : Extends the above by registering the
PublishDomainEventsInterceptoras a singleton and adding it to the DbContext options, enabling automatic domain event dispatch on save. - AddUnitOfWork : Registers the
UnitOfWork<TDbContext>as scoped, binding it to bothIUnitOfWorkand theDbContextso that all scoped services share the same context instance. - AddCommandRepositories / AddQueryRepositories / AddDomainRepositories : Registers all concrete types implementing the respective marker interfaces by scanning a given assembly.
- AddDomainServices : Registers all concrete types implementing
IDomainServiceby scanning a given assembly.
Interceptors
The PublishDomainEventsInterceptor is an internal sealed SaveChangesInterceptor that automatically collects and dispatches domain events during SaveChanges. Before saving, it scans the ChangeTracker for entities implementing IEntity, collects their domain events, and clears them from the entities. After saving, it resolves an IDomainEventPublisher from a new service scope and publishes each event using cached reflection method info for performance.
Unit of Work
The UnitOfWork<TDbContext> is an internal sealed class implementing IUnitOfWork and IAsyncDisposable. It lazily creates a DbContext from an IDbContextFactory, exposes a SaveChangesAsync method to persist changes, and disposes the context asynchronously when the unit of work scope ends.