Dependency Injection MVC C # - MongoDB 2.0

3

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

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

Thank you.

    
asked by anonymous 13.01.2016 / 18:37

1 answer

2

MongoDB Driver Dependency Injection

The MongoDB driver is tightly coupled so you will not be able to modify the driver's features easily since it does not use external dependencies (you're certainly not trying to do this) if you intend to use 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 allow you access to database management methods (creation of new banks, deletion and listing, obtaining a single bank) Reference: link

MongoDB.Driver.IMongoDatabase : Interface responsible for specifying a mongodb collection will allow you access to the collection management methods (creation, deletion and listing, obtaining, renaming and executing commands) Reference: link

MongoDB.Driver.IMongoCollection < > : Interface responsible for specifying mongo document collections different from other interfaces collections are generic ie you will have to specify a type for collections Ex: IMongoCollection < Product > the collections will allow you access to the records through the methods of query, deletion, editing, insertion, among others. Reference: link

As for a pattern to use, here's an example of implementing 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 link for the repository code

    
13.01.2016 / 19:49