【发布时间】:2021-11-22 23:57:56
【问题描述】:
所以我和同事讨论了从基类到接口的合同实现。
我们的 DDD 结构如下,Api -> Application -> Domain -> Infrastructure。 在基础架构中,我们使用 EF Core。
以下代码示例
应用程序
public interface IOrderRepository
{
IUnitOfWork UnitOfWork { get; }
Task AddOrderAsync(Order order);
}
基础设施
public class OrderRepository : BaseRepository<Order, DbContext>, IOrderRepository
{
public OrderRepository(DbContext ctx) : base(ctx) { }
public async Task AddOrderAsync(Order order)
{
try
{
await AddAsync(order);
}
catch (Exception ex)
{
Log.Error($"Exception: {ex}");
throw ex;
}
}
/*
*
* Some other db methods
*
*/
}
public abstract class BaseRepository<T, U> where T : class where U : BaseDbContext, IUnitOfWork
{
protected readonly U _context;
public IUnitOfWork UnitOfWork
{
get
{
return _context;
}
}
public BaseRepository(U context)
{
_context = context;
}
protected virtual async Task AddAsync(T entity)
{
await _context.Set<T>().AddAsync(entity);
}
}
所以我主张,而不是在每个存储库中实现 AddNAMEAsync 方法,以在基类和相应的接口中使 AddAsync public virtual 并利用基类实现。这样,我们仍然可以在需要时订购 AddAsync,并最大限度地减少存储库中不必要的“重复代码”。
另一方面,我的同事认为这会使名称过于笼统,并且在调用存储库时,您仅通过阅读代码就不会知道要添加到上下文中的实体。并且还争论说我们不应该在接口中公开基类方法,而应该只公开 Parent -> Child。
我们使用 SOLID 原则,每个处理程序只处理一个实体/域聚合,我们对变量/对象也有非常清晰的命名,因此您可以轻松地在存储库名称以及在上下文中看到您要添加的内容领域模型
【问题讨论】:
标签: c# architecture entity-framework-core domain-driven-design