db: refactor to only init mongo client & collections once

This commit is contained in:
Abdullah Atta
2024-06-07 15:39:12 +05:00
parent c5b41be2fd
commit 99f095babe
4 changed files with 23 additions and 57 deletions
@@ -31,20 +31,14 @@ namespace Streetwriters.Data.Repositories
public class Repository<TEntity> where TEntity : class
{
protected readonly IDbContext dbContext;
protected IMongoCollection<TEntity> Collection { get; set; }
public IMongoCollection<TEntity> Collection { get; set; }
public Repository(IDbContext _dbContext, string databaseName, string collectionName)
public Repository(IDbContext _dbContext, IMongoCollection<TEntity> collection)
{
dbContext = _dbContext;
Collection = GetCollection(databaseName, collectionName);
Collection = collection;
}
private protected IMongoCollection<TEntity> GetCollection(string databaseName, string collectionName)
{
return dbContext.GetCollection<TEntity>(databaseName, collectionName);
}
public virtual void Insert(TEntity obj)
{
dbContext.AddCommand((handle, ct) => Collection.InsertOneAsync(handle, obj, null, ct));