I've got a RESTful backend using mongodb as an underlying storage. I'm using c# driver. Documentation states that mongo manages its connection pool by itself.
The question is: to communicate with mongodb I need the instances of the following implementations
IMongoClient
IMongoDatabase
IMongoCollection<T>
What are the best practices to manage lifetime of these objects? I can store them with singleton lifestyle per server (appdomain) or I can keep creating them per request. For now only IMongoCollection<T>
is per request.
The recommended way is to hold a single MongoClient
instance and use it to get your databases and collections when you need them.
You may aggressively cache all these instances if it's critical for your performance however in most cases that's unnecessary as all these types are very simple and cheap to create. For example this is the GetCollection
method:
public override IMongoCollection<TDocument> GetCollection<TDocument>(string name, MongoCollectionSettings settings)
{
Ensure.IsNotNullOrEmpty(name, "name");
settings = settings == null ?
new MongoCollectionSettings() :
settings.Clone();
settings.ApplyDefaultValues(_settings);
return new MongoCollectionImpl<TDocument>(this, new CollectionNamespace(_databaseNamespace, name), settings, _cluster, _operationExecutor);
}
Other than some argument handling and a couple of allocations there's really nothing being done here. What's actually expensive is the connection pooling and (as you mentioned) it's handled by the driver internally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With