MongoDbRepositoryCore 6.2.0
See the version list below for details.
dotnet add package MongoDbRepositoryCore --version 6.2.0
NuGet\Install-Package MongoDbRepositoryCore -Version 6.2.0
<PackageReference Include="MongoDbRepositoryCore" Version="6.2.0" />
<PackageVersion Include="MongoDbRepositoryCore" Version="6.2.0" />
<PackageReference Include="MongoDbRepositoryCore" />
paket add MongoDbRepositoryCore --version 6.2.0
#r "nuget: MongoDbRepositoryCore, 6.2.0"
#:package MongoDbRepositoryCore@6.2.0
#addin nuget:?package=MongoDbRepositoryCore&version=6.2.0
#tool nuget:?package=MongoDbRepositoryCore&version=6.2.0
📖 MongoDbRepository v6.2 (.NET 10 & C# 13)
Welcome to the production runtime engine for MongoDbRepository v6.2. Fully optimized for .NET 10 and C# 13, this core framework provides an explicit, high-performance data access layer built directly on top of the official MongoDB C# Driver v3.8.1.
Version 6.2 introduces single-roundtrip atomic upserts, binary SHA256 query cache key hashing, channel-backed distributed cache invalidation, and targeted assembly scanning.
🌟 Core Pillars of Enterprise Hardening
1. Hardened Domain Immutability
Domain entity definitions enforce strict data integrity constraints. Primary identifier properties utilize native C# init accessors, completely eliminating downstream key mutations and ensuring client-side domain models align with database-level primary key immutability rules.
2. Thread-Safe Ambient Transactions
Multi-document mutations share database execution contexts across async stack continuations safely using an AsyncLocal session handle. Internal modifications are protected by a localized coordination gate (LockObject), ensuring thread-safe processing inside parent transaction contexts. Furthermore, an explicit fallback boundary timeout (maxCommitTime) prevents long-running pipeline locks from stalling connection pools.
3. Single-Roundtrip Atomic Upserts ($setOnInsert, $set, $inc)
The repository's UpsertAsync method is fully optimized to eliminate TOCTOU (Time-of-Check to Time-of-Use) race conditions in a single atomic database roundtrip.
IAuditableEntity: SetsCreatedAton insertion via$setOnInsertwithout overwriting existing timestamps on updates, and$set: UpdatedAt.IVersionedEntity: Uses$inc: { Version: 1 }to atomically initialize versioning to1on insertion and increment on update while enforcing optimistic concurrency version checks.- In-Memory Sync: Automatically updates
document.CreatedAt,document.UpdatedAt, anddocument.Versionon the caller's in-memory instance post-upsert.
4. Binary SHA256 Query Cache Key Hashing
Query filter list caching via GetManyAsync uses CacheKeyBuilder.ComputeQueryHash to generate a 256-bit SHA256 hex hash directly from raw BSON binary bytes (ToBson()). This bypasses JSON string formatting (ToJson()) overhead and eliminates heap string allocations on hot read paths.
5. Multi-Tier Memory & Channel-Backed Eviction
- Local Tier: Prefix-based cancellation tokens (
_ExpirationSignal) invalidate complex query caches instantly on writes. - Distributed Tier: Secondary-tier distributed cache eviction (e.g., Redis) is offloaded to a lock-free
System.Threading.Channelsqueue drained byDistributedCacheEvictionBackgroundService. Auto-registered out-of-the-box viaAddMongoDbRepositoryCore.
6. Targeted Assembly Scanning
AddAutomatedIndexes and GenericCacheWarmerHostedService use AssemblyScanner to filter out framework and system assemblies (System.*, Microsoft.*, netstandard), avoiding expensive recursive Assembly.Load crawling loops. Supports explicit assembly parameters (e.g. AddAutomatedIndexes(typeof(MyIndexProvider).Assembly)).
7. Pessimistic Outbox Leases
The real-time change-stream engine and the background fallback sweeper are fully guarded against processing duplication across horizontally scaled container instances. Messages must secure an atomic database-level row lease (FindOneAndUpdateAsync modifying LockedUntil) before execution, ensuring single-delivery event guarantees.
🚀 Quick Setup & Registration
1. Update Core Configurations (appsettings.json)
Inject configuration connection strings alongside fallback boundaries and outbox system collection names:
{
"MongoDb": {
"ConnectionString": "mongodb://username:password@localhost:27017/?replicaSet=rs0",
"DatabaseName": "CorporateFintechDb",
"DefaultTransactionTimeout": "00:00:05",
"SystemCollections": {
"Outbox": "System_Outbox",
"AuditLogs": "System_AuditLogs"
}
}
}
2. Bootstrap Dependencies (Program.cs)
Register the repository structures, channel eviction queues, transaction managers, and dynamic index migration services using chainable extension builders:
var builder = WebApplication.CreateBuilder(args);
// 1. Register core Mongo connections, transaction handlers, open-generic repositories, and channel eviction queues
builder.Services.AddMongoDbRepositoryCore(builder.Configuration.GetSection("MongoDb"));
// 2. Scans specific domain assemblies, registers index blueprints, and attaches index verification workers
builder.Services.AddAutomatedIndexes(typeof(CreditFacilityIndexProvider).Assembly);
3. Initialize Mappings on Boot
Compile and register your process BSON class maps safely on application startup:
var app = builder.Build();
// Run domain class profiles safely without crash risks inside parallel test runners
app.Services.InitializeMongoMappings();
app.Run();
🛠 Core Coding Blueprints
1. Creating Immutable Domain Models
Inherit from BaseDocument<TId> to take advantage of compile-time identifier immutability:
using System;
using MongoDB.Bson;
using MongoDbRepository.Core.Models;
using MongoDbRepository.Core.Interfaces;
using MongoDbRepository.Interfaces;
namespace CorporateLending.Domain.Models;
public class CreditFacility : BaseDocument<ObjectId>, IVersionedEntity, IAuditableEntity, ISoftDeletable
{
public string CorporateId { get; init; } = string.Empty;
public decimal ApprovedLimit { get; set; }
// Concurrency & Operational Invariants
public int Version { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
// Soft Deletion
public bool IsDeleted { get; set; }
public DateTime? DeletedAt { get; set; }
}
2. Executing Single-Roundtrip Atomic Upserts
public class FacilityService(IBaseRepository<CreditFacility, ObjectId> facilityRepo)
{
public async Task UpsertFacilityAsync(CreditFacility facility, CancellationToken cancellationToken)
{
// Executes atomic $setOnInsert, $set, and $inc in a single database roundtrip,
// automatically updating facility.CreatedAt, facility.UpdatedAt, and facility.Version in memory
await facilityRepo.UpsertAsync(facility, null, cancellationToken);
}
}
3. Executing Safe, Thread-Guarded Transactions
Inject IMongoTransactionManager to coordinate multi-collection execution workflows safely:
public class LoanProcessingService(
IMongoTransactionManager transactionManager,
IBaseRepository<CreditFacility, ObjectId> facilityRepository)
{
public async Task ProcessApprovalAsync(CreditFacility facility, CancellationToken cancellationToken)
{
await transactionManager.ExecuteTransactionAsync(async session =>
{
await facilityRepository.AddAsync(facility, session, cancellationToken);
// Multi-collection mutations chained here...
}, cancellationToken);
// Post-commit cache invalidation triggers cleanly AFTER the server commits
}
}
4. Streaming High-Throughput Reports
Inject IReadOnlyRepository<TDocument, TId> to bypass query caches and stream datasets directly from the network socket:
public class RiskReportingController(IReadOnlyRepository<CreditFacility, ObjectId> readOnlyRepo) : ControllerBase
{
[HttpGet("stream-active")]
public async Task StreamFacilitiesAsync(CancellationToken cancellationToken)
{
var filter = Builders<CreditFacility>.Filter.Gt(x => x.ApprovedLimit, 10000000);
await foreach (var facility in readOnlyRepo.StreamManyAsync(filter, null, cancellationToken))
{
await Response.WriteAsJsonAsync(facility, cancellationToken);
}
}
}
🔒 Automated Testing & Mockless Verification
Use the built-in thread-safe InMemoryRepository substitute for fast unit testing with zero configuration overhead:
[Fact]
public async Task CalculateTotalExposure_ShouldFilterSoftDeletedRecords()
{
var fakeRepo = new InMemoryRepository<CreditFacility, ObjectId>();
var activeId = ObjectId.GenerateNewId();
var deletedId = ObjectId.GenerateNewId();
fakeRepo.Seed([
new CreditFacility { Id = activeId, ApprovedLimit = 5000000, IsDeleted = false },
new CreditFacility { Id = deletedId, ApprovedLimit = 2000000, IsDeleted = true }
]);
var service = new ExposureCalculator(fakeRepo);
decimal totalExposure = await service.GetActiveExposureAsync();
Assert.Equal(5000000, totalExposure); // Confirms soft-delete filters are respected
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- FluentValidation (>= 12.1.1)
- MediatR (>= 14.1.0)
- Microsoft.AspNetCore.DataProtection (>= 10.0.9)
- Microsoft.AspNetCore.DataProtection.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Caching.Memory (>= 10.0.9)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 10.0.8)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.9)
- Microsoft.Extensions.Options (>= 10.0.9)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.9)
- MongoDB.Driver (>= 3.8.1)
- Polly (>= 8.6.6)
- SharpCompress (>= 0.49.1)
NuGet packages (15)
Showing the top 5 NuGet packages that depend on MongoDbRepositoryCore:
| Package | Downloads |
|---|---|
|
MongoDbRepository.Extensions.Outbox.MessageBus
Package Description |
|
|
MongoDbRepository.Extensions.Aspire
Package Description |
|
|
MongoDbRepository.Extensions.Audit.Cryptography
Package Description |
|
|
MongoDbRepository.Extensions.DataMesh.Bridge
Package Description |
|
|
MongoDbRepository.Extensions.Polly.Resiliency
Package Description |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 6.4.3 | 1,235 | 8/14/2026 |
| 6.4.2 | 229 | 8/7/2026 |
| 6.4.0 | 243 | 8/5/2026 |
| 6.3.2 | 256 | 8/1/2026 |
| 6.3.1 | 215 | 8/1/2026 |
| 6.3.0 | 206 | 7/24/2026 |
| 6.2.0 | 107 | 7/24/2026 |
| 6.1.6 | 116 | 7/19/2026 |
| 6.1.4 | 112 | 7/14/2026 |
| 6.1.3 | 111 | 7/14/2026 |
| 6.1.2 | 119 | 7/5/2026 |
| 6.1.1 | 164 | 7/1/2026 |
| 6.1.0 | 155 | 6/30/2026 |
| 6.0.17 | 130 | 6/29/2026 |
| 6.0.16 | 125 | 6/26/2026 |
| 5.0.4 | 125 | 5/14/2026 |
| 5.0.3 | 113 | 4/30/2026 |
| 5.0.2 | 116 | 4/25/2026 |
| 5.0.1 | 114 | 4/23/2026 |
| 5.0.0 | 137 | 4/21/2026 |