MVC C# dependency injection – MongoDB 2.0

Question:

I'm starting a project using MVC 4 with MongoDB Driver 2.0. I'm used to using Ninject with EF6 and would like to know if there is something like that for MongoDB or some example architecture pattern to implement it.

Ps: I've already found some examples using the old driver, but I'm implementing the new one from MongoDB .

Thanks.

Answer:

MongoDB Driver Dependency Injection

The MongoDB driver is tightly coupled so you won't be able to easily modify the driver's functionality as it doesn't use external dependencies (You're certainly not trying to do that) if you intend to use MongoDB through an injection system of dependency you will need to implement or transfer objects based on the interfaces below:

MongoDB.Driver.IMongoClient : Interface responsible for specifying a mongodb client will allow you to access database management methods (creating new databases, deleting 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 allow you access to collection management methods (creating, deleting and listing, obtaining, renaming and executing commands) Reference:http://api.mongodb. org/csharp/2.0/html/T_MongoDB_Driver_IMongoDatabase.htm

MongoDB.Driver.IMongoCollection<> : Interface responsible for specifying mongo document collections different from the other interfaces the collections are generic, that is, you will have to specify a type for the collections Ex: IMongoCollection< Product> the collections will allow you to access them 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, here is an example of implementing the 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 for the code referring to the repository

Scroll to Top