MongoDbRepositoryCore 6.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MongoDbRepositoryCore --version 6.2.0
                    
NuGet\Install-Package MongoDbRepositoryCore -Version 6.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MongoDbRepositoryCore" Version="6.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MongoDbRepositoryCore" Version="6.2.0" />
                    
Directory.Packages.props
<PackageReference Include="MongoDbRepositoryCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MongoDbRepositoryCore --version 6.2.0
                    
#r "nuget: MongoDbRepositoryCore, 6.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MongoDbRepositoryCore@6.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MongoDbRepositoryCore&version=6.2.0
                    
Install as a Cake Addin
#tool nuget:?package=MongoDbRepositoryCore&version=6.2.0
                    
Install as a Cake Tool

📖 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: Sets CreatedAt on insertion via $setOnInsert without overwriting existing timestamps on updates, and $set: UpdatedAt.
  • IVersionedEntity: Uses $inc: { Version: 1 } to atomically initialize versioning to 1 on insertion and increment on update while enforcing optimistic concurrency version checks.
  • In-Memory Sync: Automatically updates document.CreatedAt, document.UpdatedAt, and document.Version on 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.Channels queue drained by DistributedCacheEvictionBackgroundService. Auto-registered out-of-the-box via AddMongoDbRepositoryCore.

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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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
Loading failed