mongodbrepositoryirepository

MongoDB IRepository db Connections


This is what I have so far with regards to my IRepository for MongoDB and was wondering whether or not I'm on the right lines?

public abstract class Repository<TEntity> : IRepository<TEntity> {

    private const string _connection = "mongodb://localhost:27017/?safe=true";
    private MongoDatabase _db;
    protected abstract string _collection{get;}

    public Repository() {
        this._db = MongoServer.Create(_connection).GetDatabase("Photos");
    }

    public IQueryable<TEntity> FindAll() {

        return this._db.GetCollection<TEntity>(_collection).FindAll().AsQueryable();
    }
}

This way I can create my PhotoRepository class that inherits from here and supplies the required _collection name.

I just want to make sure that I'm opening the connection to the db in the correct place and in the correct way.


Solution

  • Yes, this is fine. MongoServer.Create will return the same instance of MongoServer when passed the same connection string, so it is safe to call MongoServer.Create as many times as you want.