using MongoDB.Driver; using MongoDbGenericRepository.Models; namespace MongoDbGenericRepository { /// /// The MongoDb context /// public class MongoDbContext : IMongoDbContext { /// /// The IMongoClient from the official MongoDb driver /// public IMongoClient Client { get; } /// /// The IMongoDatabase from the official Mongodb driver /// public IMongoDatabase Database { get; } static MongoDbContext() { // Avoid legacy UUID representation: use Binary 0x04 subtype. MongoDefaults.GuidRepresentation = MongoDB.Bson.GuidRepresentation.Standard; } /// /// The constructor of the MongoDbContext, it needs a an object implementing . /// /// An object implementing IMongoDatabase public MongoDbContext(IMongoDatabase mongoDatabase) { Database = mongoDatabase; Client = Database.Client; } /// /// The constructor of the MongoDbContext, it needs a connection string and a database name. /// /// The connections string. /// The name of your database. public MongoDbContext(string connectionString, string databaseName) { Client = new MongoClient(connectionString); Database = Client.GetDatabase(databaseName); } /// /// The private GetCollection method /// /// /// public IMongoCollection GetCollection() { return Database.GetCollection(Pluralize()); } /// /// Returns a collection for a document type that has a partition key. /// /// /// The value of the partition key. public IMongoCollection GetCollection(string partitionKey) where TDocument : IDocument { return Database.GetCollection(partitionKey +"-"+ Pluralize()); } /// /// Drops a collection, use very carefully. /// /// public void DropCollection() { Database.DropCollection(Pluralize()); } /// /// Drops a collection having a partitionkey, use very carefully. /// /// public void DropCollection(string partitionKey) { Database.DropCollection(partitionKey + "-" + Pluralize()); } /// /// Very naively pluralizes a TDocument type name. /// /// /// private string Pluralize() { return (typeof(TDocument).Name.Pluralize()).Camelize(); } } }