Mongodb Driver Dependency Injection
The driver of MongoDB
is strongly coupled or you will not be able to modify the driver’s functionality easily since it does not use external dependencies (you are certainly not trying to do this), if you intend to use the MongoDB
through a dependency injection system you will need to implement or transfer objects based on the interfaces below:
Mongodb.Driver.Imongoclient:
Interface responsible for specifying a mongodb client will give you access to database management methods (creating new databases, deletion and listing, obtaining a single database)
Reference: http://api.mongodb.org/csharp/2.0/html/T_MongoDB_Driver_IMongoClient.htm
Mongodb.Driver.Imongodatabase:
Interface responsible for specifying a mongodb collection will give you access to collection management methods (creation, deletion and listing, retrieval, renaming and command execution)
Reference: http://api.mongodb.org/csharp/2.0/html/T_MongoDB_Driver_IMongoDatabase.htm
Mongodb.Driver.Imongocollection<>:
Interface responsible for specifying Ngo document collections different from other interfaces the collections are generic or you will need to specify a type for the collections Ex: Imongocollection< Product> the collections will allow you access to the records through the methods of consultation, deletion, editing, insertion, among others.
Reference: http://api.mongodb.org/csharp/2.0/html/T_MongoDB_Driver_IMongoCollection_1.htm
As for a Pattern to use, an example of the implementation of Repository Pattern
with Mongodb:
public class Repository<T> : IRepository<T> where T : new()
{
protected readonly MongoClient client;
protected readonly MongoServer server;
protected readonly MongoDatabase database;
protected readonly MongoCollection collection;
public Repository(MongoClient client, MongoServer server, MongoDatabase database, MongoCollection collection)
{
this.client = client;
this.server = server;
this.database = database;
this.collection = collection;
}
// Exemplo de adição de novos elementos em uma coleção.
public void Add(T entity)
{
this.collection.Save(entity);
}
}
Credits to https://github.com/fagnercarvalho by the code referring to the repository
Thanks Felipe for the collaboration. However, I did not want to rewrite the interfaces of Mongo for injection. Regarding the repository thanks for the tip but I’m already using a Generic Repository also in the project.
– Jhonathan
You don’t need to implement the interfaces just register the concrete classes of the Mongo in your container.
– Felipe Assunção