using MongoDB.Driver; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace MisIngredientesVue.Core.Services { public interface ILogRepository { IMongoCollection Collection { get; } IMongoDatabase Database { get; } Task InsertAsync(T entity); } public class LogRepository : ILogRepository { protected IMongoCollection _collection; public IMongoCollection Collection { get { return _collection; } } protected IMongoDatabase _database; public IMongoDatabase Database { get { return _database; } } public LogRepository() { string connectionString = "mongodb://localhost/logs"; if (!string.IsNullOrEmpty(connectionString)) { var client = new MongoClient(connectionString); var databaseName = new MongoUrl(connectionString).DatabaseName; _database = client.GetDatabase(databaseName); _collection = _database.GetCollection(typeof(T).Name); } } public LogRepository(string connectionString) { var client = new MongoClient(connectionString); var databaseName = new MongoUrl(connectionString).DatabaseName; _database = client.GetDatabase(databaseName); _collection = _database.GetCollection(typeof(T).Name); } public LogRepository(IMongoClient client) { string connectionString = "mongodb://localhost/logs"; var databaseName = new MongoUrl(connectionString).DatabaseName; _database = client.GetDatabase(databaseName); _collection = _database.GetCollection(typeof(T).Name); } public LogRepository(IMongoDatabase database) { _database = database; _collection = _database.GetCollection(typeof(T).Name); } public virtual async Task InsertAsync(T entity) { try { await _collection.InsertOneAsync(entity); return entity; } catch(Exception ex) { Console.WriteLine($"[ERROR] LogRepository.InsertAsync {ex.Message}"); return default(T); } } } }