Skip to content

Initialize MongoDbContext from IMongoClient for Aspire Support #103

@philbir

Description

@philbir

Feature Request: Support IMongoClient Injection in MongoDbContext

Summary

When using .NET Aspire with MongoDB, the Aspire.MongoDB.Driver.v3 package registers an IMongoClient in the dependency injection (DI) container.

However, the current MongoDbContext does not provide a constructor that accepts an IMongoClient. This makes it difficult to leverage the existing DI registration without introducing unnecessary or "ugly" workarounds (e.g., resolving the client manually or duplicating configuration).


Proposed Solution

Add an additional constructor to MongoDbContext that accepts an IMongoClient:

public class MongoDbContext
{
    public MongoDbContext(IMongoClient mongoClient, string databaseName)
    {
        Database = mongoClient.GetDatabase(databaseName);
    }

    public IMongoDatabase Database { get; }
}

This aligns with the standard DI pattern and allows developers to take full advantage of the already-registered IMongoClient from Aspire.MongoDB.Driver.v3.


Benefits

  • Cleaner DI Integration: No need to manually create or configure MongoDB clients outside DI.
  • Consistency: Matches patterns from other database providers in Aspire.
  • Improved Testability: Easier to mock IMongoClient for unit tests.

References

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions