MongoDbRepositoryCore 5.0.4

dotnet add package MongoDbRepositoryCore --version 5.0.4
                    
NuGet\Install-Package MongoDbRepositoryCore -Version 5.0.4
                    
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="5.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MongoDbRepositoryCore" Version="5.0.4" />
                    
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 5.0.4
                    
#r "nuget: MongoDbRepositoryCore, 5.0.4"
                    
#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@5.0.4
                    
#: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=5.0.4
                    
Install as a Cake Addin
#tool nuget:?package=MongoDbRepositoryCore&version=5.0.4
                    
Install as a Cake Tool

Here are the updated documentation files for v5.0. I have incorporated all the enterprise hardening features we just implemented, including the strict Outbox transaction enforcement, BSON-native distributed caching, OOM-safe preloading, and the single-trip aggregation optimizations.

  1. README.md Markdown

📖 MongoDbRepository Developer's Guide (v5.0.0)

Welcome to the daily cookbook for the MongoDbRepository framework. This guide covers how to leverage the advanced v5.0 features, including Zero-Boilerplate Source Generators, AI Semantic Search, Microservices Caching, the Outbox Pattern, and Code-First Migrations.


🌟 What's New in V5: Enterprise Hardening

Version 5 introduces massive stability and performance improvements for enterprise production environments:

  • Strict ACID Outbox: The Outbox pattern now strictly enforces ambient transactions. If you attempt to save an entity with pending domain events outside of a transaction, the repository fails fast to prevent data corruption.
  • BSON-Native Distributed Caching: Redis caching now utilizes native BSON wrappers instead of JSON, perfectly preserving ObjectId references, custom encryption conventions, and [BsonIgnore] attributes across your distributed cluster.
  • OOM-Safe Preloading: Cache preloading now safely caps at 10,000 items to prevent startup crashes on massive collections.
  • Single-Trip Aggregations: SumAsync and AverageAsync now calculate in a single network round-trip, halving database latency.
  • Clean Architecture DI: BaseService now enforces explicit constructor injection, dropping the legacy Service Locator anti-pattern.

1. Zero-Boilerplate DI

Forget manually registering dozens of repositories and services. V5 uses a blazing-fast Roslyn Source Generator (C# 7.3+ compliant) that wires up your entire database layer at compile-time.

Step 1: Add the [GenerateRepository] attribute to your entity.

[GenerateRepository]
[Cacheable(IsDistributed = true)] // Optional: Stacks the BSON-native distributed caching decorator!
public class User : Entity 
{
    public string Name { get; set; }
}
Step 2: Call the auto-generated extension method in Program.cs. The generator automatically maps the interfaces, applies your decorators, and registers MediatR for background tasks.

C#
builder.Services.AddAutoGeneratedMongoRepositories();
builder.Services.AddAutoGeneratedMongoServices();
2. Generative AI & Vector Search
MongoDB Atlas supports native AI Vector Searches. This library reduces complex aggregation pipelines into a single attribute and method call.

Step 1: Add the [VectorEmbedding] attribute to a float[] property on your entity. The repository will automatically provision the Atlas Search Indexes on startup.

C#
public class SupportArticle : Entity
{
    public string Title { get; set; }
    public string Content { get; set; }

    [VectorEmbedding(Dimensions = 1536, Similarity = "cosine")]
    public float[] ContentEmbedding { get; set; } 
}
Step 2: Execute a Semantic Search natively.

C#
// Generate embedding via OpenAI, HuggingFace, etc.
float[] userQuestionVector = await _aiService.GetEmbeddingAsync("How do I reset my password?");

// Search, with optional pre-filtering!
var topArticles = await _articleRepo.SemanticSearchAsync(
    queryVector: userQuestionVector, 
    limit: 5, 
    filter: article => article.IsActive // Pre-filters using standard LINQ
);
3. The Transactional Outbox Pattern (Guaranteed Events)
In a distributed system, saving a database record and firing an event is dangerous. If the server crashes between the two, the event is lost. V5 handles this flawlessly with a Zero-Config Outbox.

When you attach an event using IHasDomainEvents, the repository serializes the MediatR event into a System_Outbox collection inside an ACID transaction. Note: In V5, attempting to save an entity with events outside of IMongoTransactionManager will throw a safeguard exception.

C#
using var transaction = await _transactionManager.BeginTransactionAsync();

user.AddDomainEvent(new UserRegisteredEvent(user.Id));
await _userRepo.AddAsync(user); // 100% Guaranteed Delivery

await transaction.CommitAsync();
4. Distributed Cluster Caching (Redis)
If you run multiple instances of your API (e.g., in Kubernetes), standard RAM caching leads to stale data. Use [Cacheable(IsDistributed = true)] to utilize the DistributedCachingRepositoryDecorator.

If Pod A updates a user, it deletes the key from Redis, meaning Pods B, C, and D instantly fetch fresh data on their next request.

C#
builder.Services.AddMongoDbRepositories(db => { ... }, cache => 
{
    cache.ApplicationName = "BillingApi"; 
});
5. Code-First Migrations
Need to seed an Admin user or rename a property across 1 million documents? Write a migration script. The framework will automatically run it on application startup and track its execution.

C#
public class Migration_001_SeedAdmin : IMongoMigration
{
    public int Version => 1;

    public async Task UpAsync(IMongoDatabase database)
    {
        var users = database.GetCollection<User>("users");
        await users.InsertOneAsync(new User { Email = "admin@system.com", Role = "SuperAdmin" });
    }
}
6. Mockless Unit Testing
Stop mocking IMongoCollection! We ship a blazing-fast, thread-safe fake that implements IRepository<T, TId> and executes your queries in memory.

C#
[Fact]
public async Task GetActiveUsers_ReturnsCorrectData()
{
    // Arrange: Use the fake repository (0 milliseconds execution!)
    var fakeRepo = new InMemoryRepository<User, Guid>();
    fakeRepo.Seed(new[] { new User { Id = Guid.NewGuid(), IsActive = true, Name = "Alice" } });

    var service = new UserService(fakeRepo);

    // Act
    var activeUsers = await service.GetActiveUsersAsync();

    // Assert
    Assert.Single(activeUsers); 
}
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.0.4 102 5/14/2026
5.0.3 94 4/30/2026
5.0.2 96 4/25/2026
5.0.1 89 4/23/2026
5.0.0 109 4/21/2026
4.5.10 108 4/13/2026
4.5.4 102 4/10/2026
4.5.3 95 4/9/2026
4.5.2 96 4/9/2026
4.5.1 99 4/9/2026
4.1.0 100 4/9/2026
4.0.0 109 3/25/2026
3.4.5 112 3/20/2026
3.4.0 100 3/20/2026
3.3.0 109 3/20/2026
3.2.2 111 3/15/2026
3.2.1 107 3/15/2026
3.2.0 111 3/14/2026
3.1.0 108 3/6/2026
3.0.2 111 3/1/2026
Loading failed