MongoDbRepositoryCore 6.1.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package MongoDbRepositoryCore --version 6.1.3
                    
NuGet\Install-Package MongoDbRepositoryCore -Version 6.1.3
                    
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.1.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MongoDbRepositoryCore" Version="6.1.3" />
                    
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.1.3
                    
#r "nuget: MongoDbRepositoryCore, 6.1.3"
                    
#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.1.3
                    
#: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.1.3
                    
Install as a Cake Addin
#tool nuget:?package=MongoDbRepositoryCore&version=6.1.3
                    
Install as a Cake Tool

📖 MongoDbRepository v6.0 (.NET 10 & C# 13) Welcome to the production runtime engine for MongoDbRepository v6.0. Fully optimized for .NET 10 and C# 13, this core framework provides an explicit, zero-allocation, ultra-high-performance data access layer built directly on top of the official MongoDB C# Driver v3.x.

Version 6.0 abandons the implicit v5 proxy code generation and black-box decorators in favor of direct type verification, structural immutability, and thread-safe background coordination.

🌟 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 perfectly 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. Prefix-Based Memory Cache Invalidation Complex, filtered list queries are cached locally using an advanced signal grouping engine. All filtered variations of a collection are bound via a CancellationChangeToken to a master collection prefix _ExpirationSignal key. Executing any write command cancels this token, instantly evicting all complex query hashes for that collection simultaneously.

  4. Structured Concurrency Cache Eviction Secondary-tier distributed cache invalidation (e.g., Redis) has been decoupled from the application request-response thread pool. Eviction closures are offloaded to lock-free, high-throughput System.Threading.Channels channels, which are drained sequentially by a dedicated background service. This guarantees cache synchronization even during sudden application container recycling or scale-down events.

  5. TOCTOU-Safe Atomic Upserts The repository eliminates client-side Time-of-Check to Time-of-Use (TOCTOU) race windows. For standard entities, it executes a single atomic database-level replacement. For versioned or auditable entities, it safely runs a guarded insert path, intercepts duplicate key errors natively, re-hydrates baselines from the server, and automatically transitions to an optimistic concurrency update check.

  6. 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 strict single-delivery event guarantees under peak ingestion load.

🚀 Quick Setup & Registration

  1. Update Core Configurations (appsettings.json) Inject configuration connection strings alongside fallback boundaries and outbox system collection names:
JSON
{
  "MongoDb": {
    "ConnectionString": "mongodb://username:password@localhost:27017/?replicaSet=rs0",
    "DatabaseName": "CorporateFintechDb",
    "DefaultTransactionTimeout": "00:00:05",
    "SystemCollections": {
      "Outbox": "System_Outbox",
      "AuditLogs": "System_AuditLogs"
    }
  }
}
  1. Bootstrap Dependencies (Program.cs) Register the zero-allocation repository structures, channel queues, and dynamic index migration services using clear, chainable extension builders:
C#
var builder = WebApplication.CreateBuilder(args);

// Register core Mongo connections, transaction handlers, and open-generic repositories
builder.Services.AddMongoDbRepositoryCore(builder.Configuration.GetSection("MongoDb"));

// Scans assemblies, registers index blueprints, and attaches closed hosted workers
builder.Services.AddAutomatedIndexes();
  1. Initialize Mappings on Boot Compile and register your process BSON class maps safely on application startup. The initialization sequence contains localized type validation guards to protect your integration test suites from duplicate class map registration crashes:
C#
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. Derived constructors pass generated tracking states up via constructor chaining:
C#
using MongoDB.Bson;
using MongoDbRepository.Core.Models;
using MongoDbRepository.Interfaces;

namespace CorporateLending.Domain.Models;

public class CreditFacility : BaseDocument<ObjectId>, IVersionedEntity, IAuditableEntity
{
    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; }
}
  1. Executing Safe, Thread-Guarded Transactions Inject IMongoTransactionManager to coordinate high-throughput execution workflows safely. The manager applies strict transaction execution limits to prevent un-awaited tasks from hanging indefinitely:
C#
public class LoanProcessingService(
    IMongoTransactionManager transactionManager,
    IBaseRepository<CreditFacility, ObjectId> facilityRepository)
{
    public async Task ProcessApprovalAsync(CreditFacility facility, CancellationToken cancellationToken)
    {
        // Executes transaction bounded securely by the DefaultTransactionTimeout option
        await transactionManager.ExecuteTransactionAsync(async session =>
        {
            // Session contexts are handled automatically by the ambient context manager
            await facilityRepository.AddAsync(facility, session, cancellationToken);
            
            // Multi-collection mutations can be chained here atomically...
            
        }, cancellationToken);
        
        // Cache invalidation and post-commit handlers trigger cleanly AFTER the server commits
    }
}
  1. Streaming High-Throughput Reports Inject IReadOnlyRepository<TDocument, TId> to bypass local in-memory query caches and stream massive datasets directly from the network socket, keeping memory consumption low:
C#
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);

        // Streams data over low-overhead network cursors with soft-deletion gates enforced
        await foreach (var facility in readOnlyRepo.StreamManyAsync(filter, null, cancellationToken))
        {
            await Response.WriteAsJsonAsync(facility, cancellationToken);
        }
    }
}

🔒 Automated Testing & Mockless Verification Stop mocking complex MongoDB driver expressions. MongoDbRepository ships with a thread-safe, high-performance in-memory substitute for fast unit testing with zero configuration overhead:

C#
[Fact]
public async Task CalculateTotalExposure_ShouldFilterSoftDeletedRecords()
{
    // Arrange: Instantiate the high-speed fake repository mapping
    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);

    // Act
    decimal totalExposure = await service.GetActiveExposureAsync();

    // Assert
    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,239 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 156 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