MongoDbContext 应该是静态的吗?

Should MongoDbContext Static?

我有一个 ASP.NET Core ntier 电子商务应用程序 Mongo Db。顺便说一句,我是 MongoDb 的新手。此应用程序将在重负载下运行。

我已经创建了一个数据库上下文来连接 Mongo 数据库,但我很困惑我应该为上下文使用静态 class 吗?

Mongo 文档是这样说的:

The client instance now holds a pool of connections to the server or servers specified in the connection string.

http://mongodb.github.io/mongo-csharp-driver/2.15/getting_started/quick_tour/

还有这个:

Store your MongoClient instance in a place that is globally accessible by your application.

https://www.mongodb.com/docs/manual/administration/connection-pool-overview/

我的上下文 class 在这里,我想我应该用 Singleton with DI 来调用它。我应该怎么办?谢谢

public class MongoDbContext
{
    private readonly IMongoDatabase _database;

    public MongoDbContext(IOptions<MongoSettings> settings)
    {
        var client = new MongoClient(settings.Value.ConnectionString);
        _database = client.GetDatabase(settings.Value.Database);
    }

    public IMongoCollection<TEntity> GetCollection<TEntity>()
    {
        return _database.GetCollection<TEntity>(typeof(TEntity).Name.Trim());
    }
    public IMongoDatabase GetDatabase()
    {
        
        return _database;
    }
}

是的,每个应用程序每个集群应该只保留一个 MongoClient 实例

Use one MongoClient instance per application unless the application is connecting to many separate clusters.

MongoClient objects are thread-safe in most drivers.

Reference

您可以将其保留为 Singleton。