Workleap.Extensions.Mongo.Abstractions 1.3.1-preview.3

Prefix Reserved
This is a prerelease version of Workleap.Extensions.Mongo.Abstractions.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Workleap.Extensions.Mongo.Abstractions --version 1.3.1-preview.3                
NuGet\Install-Package Workleap.Extensions.Mongo.Abstractions -Version 1.3.1-preview.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="Workleap.Extensions.Mongo.Abstractions" Version="1.3.1-preview.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Workleap.Extensions.Mongo.Abstractions --version 1.3.1-preview.3                
#r "nuget: Workleap.Extensions.Mongo.Abstractions, 1.3.1-preview.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.
// Install Workleap.Extensions.Mongo.Abstractions as a Cake Addin
#addin nuget:?package=Workleap.Extensions.Mongo.Abstractions&version=1.3.1-preview.3&prerelease

// Install Workleap.Extensions.Mongo.Abstractions as a Cake Tool
#tool nuget:?package=Workleap.Extensions.Mongo.Abstractions&version=1.3.1-preview.3&prerelease                

Workleap.Extensions.Mongo

nuget build

Provides MongoDB access through .NET dependency injection, following Microsoft.Extensions.* library practices with several features:

  • Automatic indexes creation, update and removal based on code changes
  • Encryption at field level with different scopes (per user, tenant, or application-wide)
  • Dependency-injection enabled using IServiceCollection and IServiceProvider
  • Highly configurable (custom serializers, conventions, multiple databases support)
  • Support for multiple MongoDB connection strings and MongoDB clients
  • Roslyn analyzers for increased awareness of index usage
  • IAsyncEnumerable support

Getting started

Install the package Workleap.Extensions.Mongo.Abstractions in the project where you'll declare your documents. This package contains base classes and interfaces such as IMongoDocument, MongoIndexProvider, MongoCollectionAttribute. There's also a few extension methods of the MongoDB C# driver classes and interfaces that adds IAsyncEnumerable support to cursors.

Install the package Workleap.Extensions.Mongo at the application entry point level to register and configure the dependencies in a IServiceCollection.

Install the package Workleap.Extensions.Mongo.Ephemeral whenever you want to use a real but ephemeral MongoDB cluster with a single node replica set. This is ideal for integration testing, as each IServiceProvider will have access to an unique and isolated database.

Example

// In the project that contains the documents:
// 1) Declare the collection name (camelCase) and the type responsible for providing indexes (optional)
[MongoCollection("people", IndexProviderType = typeof(PersonDocumentIndexes))]
public class PersonDocument : IMongoDocument
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public string Name { get; set; } = string.Empty;
}

public class PersonDocumentIndexes : MongoIndexProvider<PersonDocument>
{
    public override IEnumerable<CreateIndexModel<PersonDocument>> CreateIndexModels()
    {
        // Index name is mandatory
        yield return new CreateIndexModel<PersonDocument>(
            Builders<PersonDocument>.IndexKeys.Combine().Ascending(x => x.Name),
            new CreateIndexOptions { Name = "name" });
    }
}
// 2) In the project that configures the application:
var services = new ServiceCollection();
services
    .AddMongo(ConfigureDefaultMongoClient) // <-- register the default MongoDB client and database
    .AddNamedClient("anotherClient", ConfigureAnotherMongoClient) // <-- (optional) register multiple MongoDB clients with different options and connection strings
    .AddEncryptor<YourMongoValueEncryptor>() // (optional) <-- specify how to encrypt sensitive fields
    .ConfigureStaticOptions(ConfigureMongoStatic); // (optional) <-- specify MongoDB C# driver static settings

private static void ConfigureDefaultMongoClient(MongoClientOptions options)
{
    // Simplified for demo purposes, it is better to use appsettings.json, secret vaults
    // and IConfigureOptions<> classes that can use dependency injection to access other options or dependencies
    options.ConnectionString = "mongodb://localhost";
    options.DefaultDatabaseName = "default";
    options.EnableSensitiveInformationLogging = true;

    // Used by the automatic index update feature
    options.Indexing.LockMaxLifetimeInSeconds = 300;
    options.Indexing.LockAcquisitionTimeoutInSeconds = 60;

    // Modify MongoClientSettings (optional)
    options.MongoClientSettingsConfigurator = settings => { };
    
    // EXPERIMENTAL, FOR LOCAL DEVELOPMENT ONLY:
    // This will output a warning log when a collection scan is detected on a "find" command
    options.CommandPerformanceAnalysis.EnableCollectionScanDetection = true;
}

private static void ConfigureAnotherMongoClient(MongoClientOptions options)
{
    // Define options relative to this non-default MongoDB client
    // Ideally, use IConfigureNamedOptions<MongoClientOptions>
}

private static void ConfigureMongoStatic(MongoStaticOptions options)
{    
    // There are built-in serializers and conventions registered, but you can remove or override them
    // ⚠ Careful, these are objects that will live for the entire lifetime of the application (singleton) as MongoDB C# driver
    // uses static properties to configure its behavior and serialization
    options.BsonSerializers[typeof(Foo)] = new MyFooBsonSerializer();
    options.ConventionPacks.Add(new MyConventionPack());
}

// MongoDB document properties can be encrypted when decorated with the [SensitiveInformation(scope)] attribute
// There is a convention pack that use this class to encrypt and decrypt values using a custom BsonSerializer.
// This is not required if you never use the attribute.
private sealed class YourMongoValueEncryptor : IMongoValueEncryptor
{
    // Encrypt and decrypt the bytes based on the sensitivity scope
    // Use AsyncLocal<> to determine if the sensitivity scopes matches the current execution context.
    // For instance, SensitivityScope.User should only work if there is actually an authenticated user detected through IHttpContextAccessor,
    // or any other ambient mechanism that relies on AsyncLocal<>.
    public byte[] Encrypt(byte[] bytes, SensitivityScope sensitivityScope) => bytes;
    public byte[] Decrypt(byte[] bytes, SensitivityScope sensitivityScope) => bytes;
}
// 3) Consume the registered services
// Automatically update indexes if their definition in the code has changed - a cryptographic hash is used to detect changes.
// There's a distributed lock that prevents race conditions.
// UpdateIndexesAsync() also accepts an optional registered MongoDB client name, database name and/or cancellation token. 
var indexer = this.Services.GetRequiredService<IMongoIndexer>();
await indexer.UpdateIndexesAsync(new[] { typeof(PersonDocument) });
await indexer.UpdateIndexesAsync(new[] { typeof(PersonDocument).Assembly }); // Assembly scanning alternative

// No need to know the collection name, just use the document type which must be decorated with MongoCollectionAttribute
var collection = this.Services.GetRequiredService<IMongoCollection<PersonDocument>>();
// OR: var collection = this.Services.GetRequiredService<IMongoDatabase>().GetCollection<PersonDocument>();

// No cursors handling needed, use IAsyncEnumerable
var people = await collection.Find(FilterDefinition<PersonDocument>.Empty).ToAsyncEnumerable();

// Access other registered MongoDB clients
var anotherMongoClient = this.Services.GetRequiredService<IMongoClientProvider>().GetClient("anotherClient");
// 4) Add the Workleap.Extensions.Mongo.Ephemeral package to use a ephemeral but real MongoDB database in your tests
var services = new ServiceCollection();
services.AddMongo().UseEphemeralRealServer();

Included Roslyn analyzers

Rule ID Category Severity Description
GMNG01 Design Warning Add 'IndexBy' or 'NoIndexNeeded' attributes on the containing type

In order to change the severity of one of these diagnostic rules, use a .editorconfig file, for instance:

## Disable analyzer for test files
[**Tests*/**.cs]
dotnet_diagnostic.GMNG01.severity = none

To learn more about how to configure or suppress code analysis warnings, read this documentation.

License

Copyright © 2023, Workleap. This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license at https://github.com/gsoft-inc/gsoft-license/blob/master/LICENSE.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 is compatible.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Workleap.Extensions.Mongo.Abstractions:

Package Downloads
Workleap.Extensions.Mongo

Provides MongoDB access through .NET dependency injection, following Microsoft.Extensions.* library practices.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.11.2-preview.9 37 10/30/2024
1.11.2-preview.8 34 10/28/2024
1.11.2-preview.7 33 10/28/2024
1.11.2-preview.6 34 10/28/2024
1.11.2-preview.5 36 10/16/2024
1.11.2-preview.4 34 10/7/2024
1.11.2-preview.3 42 10/1/2024
1.11.2-preview.2 47 9/30/2024
1.11.2-preview.1 49 9/27/2024
1.11.1 6,953 9/20/2024
1.11.1-preview.2 38 9/20/2024
1.11.1-preview.1 39 9/20/2024
1.11.0 2,775 8/28/2024
1.10.1-preview.17 73 8/27/2024
1.10.1-preview.16 48 8/27/2024
1.10.1-preview.15 36 8/27/2024
1.10.1-preview.14 73 8/16/2024
1.10.1-preview.13 43 8/1/2024
1.10.1-preview.12 41 8/1/2024
1.10.1-preview.11 39 8/1/2024
1.10.1-preview.10 34 7/31/2024
1.10.1-preview.9 28 7/31/2024
1.10.1-preview.8 42 7/30/2024
1.10.1-preview.7 45 7/30/2024
1.10.1-preview.6 45 7/30/2024
1.10.1-preview.5 45 7/29/2024
1.10.1-preview.4 52 7/15/2024
1.10.1-preview.3 43 7/15/2024
1.10.1-preview.1 50 6/25/2024
1.10.0 5,645 6/20/2024
1.9.3-preview.6 57 6/20/2024
1.9.3-preview.5 47 6/17/2024
1.9.3-preview.4 53 6/10/2024
1.9.3-preview.3 52 5/31/2024
1.9.3-preview.2 49 5/31/2024
1.9.3-preview.1 57 5/29/2024
1.9.2 15,362 5/27/2024
1.9.2-preview.2 46 5/27/2024
1.9.1 1,662 5/16/2024
1.9.1-preview.2 56 5/16/2024
1.9.1-preview.1 66 5/10/2024
1.9.0 3,944 5/7/2024
1.8.1-preview.1 64 5/7/2024
1.8.0 516 5/6/2024
1.7.1-preview.1 59 5/6/2024
1.7.0 518 4/29/2024
1.6.1-preview.10 46 4/29/2024
1.6.1-preview.9 61 4/22/2024
1.6.1-preview.8 68 4/16/2024
1.6.1-preview.7 55 4/15/2024
1.6.1-preview.6 66 4/12/2024
1.6.1-preview.5 56 4/11/2024
1.6.1-preview.4 71 4/3/2024
1.6.1-preview.3 58 3/8/2024
1.6.1-preview.2 55 3/7/2024
1.6.1-preview.1 54 3/4/2024
1.6.0 13,475 2/29/2024
1.5.3-preview.8 71 2/29/2024
1.5.3-preview.7 51 2/19/2024
1.5.3-preview.5 61 2/16/2024
1.5.3-preview.4 67 2/12/2024
1.5.3-preview.3 56 2/7/2024
1.5.3-preview.2 56 2/6/2024
1.5.3-preview.1 58 2/5/2024
1.5.2 4,611 1/29/2024
1.5.2-preview.7 55 1/29/2024
1.5.2-preview.6 60 1/26/2024
1.5.2-preview.5 57 1/24/2024
1.5.2-preview.4 57 1/22/2024
1.5.2-preview.3 56 1/12/2024
1.5.2-preview.2 54 1/12/2024
1.5.2-preview.1 77 12/18/2023
1.5.1 9,771 12/5/2023
1.5.1-preview.4 90 12/4/2023
1.5.1-preview.3 78 11/26/2023
1.5.1-preview.2 68 11/21/2023
1.5.1-preview.1 67 11/17/2023
1.5.0 7,265 11/16/2023
1.4.1-preview.9 73 11/15/2023
1.4.1-preview.8 72 11/13/2023
1.4.1-preview.7 69 11/7/2023
1.4.1-preview.6 84 10/30/2023
1.4.1-preview.5 78 10/13/2023
1.4.1-preview.4 73 10/13/2023
1.4.1-preview.3 83 10/6/2023
1.4.1-preview.2 83 9/27/2023
1.4.1-preview.1 75 9/26/2023
1.4.0 5,252 9/25/2023
1.3.3-preview.6 80 9/25/2023
1.3.3-preview.5 70 9/25/2023
1.3.3-preview.4 72 9/21/2023
1.3.3-preview.3 77 9/20/2023
1.3.3-preview.2 71 9/20/2023
1.3.3-preview.1 78 9/11/2023
1.3.2 4,642 9/6/2023
1.3.2-preview.1 64 9/6/2023
1.3.1 639 7/20/2023
1.3.1-preview.4 92 7/20/2023
1.3.1-preview.3 73 7/20/2023