Home > Back-end >  Should MongoDbContext Static?
Should MongoDbContext Static?

Time:05-24

I've a ASP.NET Core ntier ecommerce application with Mongo Db. I am new on MongoDb by the way. And this application will works on heavy load.

I've created a db context to connect Mongo Db but i am confused that should i use a static class for the context?

Mongo document says this :

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/

and this :

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

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

My context class is here, i think i should call it with Singleton with DI. What should i do? Thanks

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;
    }
}

CodePudding user response:

Yes, you should keep only one instance of MongoClient per cluster per application

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

MongoClient objects are thread-safe in most drivers.

Reference

You can keep that as Singleton.

  • Related