I want to implement Unit of Work for my ecommerce shop project, but I don’t understand and can’t find how to make it so repositories are gonna be generic and anytime I want to create new model my generic repository don’t violate Interface segregation principle. If, for example, I create new model, and I don`t need Update implementation it will be added anyway. I know that I can make all my repo calls in services and then only save changes in UnitOfWork, also if I will not create generic repo, I will be violating open closed principle. Here generic repo
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly ApplicationDbContext _context;
private readonly DbSet<TEntity> _dbSet;
public Repository(ApplicationDbContext context)
{
_context = context;
_dbSet = context.Set<TEntity>();
}
public async Task<TEntity> GetByIdAsync(int id)
{
return await _dbSet.FindAsync(id);
}
public async Task<IEnumerable<TEntity>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
public async Task AddAsync(TEntity entity)
{
await _dbSet.AddAsync(entity);
}
public void Update(TEntity entity)
{
_dbSet.Update(entity);
}
public void Remove(TEntity entity)
{
_dbSet.Remove(entity);
}
}
Here Unit Of Work:
public class UnitOfWork : IUnitOfWork
{
private readonly ApplicationDbContext _context;
private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>();
public UnitOfWork(ApplicationDbContext context)
{
_context = context;
}
public IRepository<TEntity> Repository<TEntity>() where TEntity : class
{
if (_repositories.ContainsKey(typeof(TEntity)))
return (IRepository<TEntity>)_repositories[typeof(TEntity)];
var repository = new Repository<TEntity>(_context);
_repositories.Add(typeof(TEntity), repository);
return repository;
}
public async Task<int> CompleteAsync()
{
return await _context.SaveChangesAsync();
}
public void Dispose()
{
_context.Dispose();
}
}
Nazar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4