我们正在开发一个ASP.NET MVC应用程序,现在正在构建存储库/服务类。我想知道,创建一个所有存储库都实现的通用IRepository接口与每个存储库都有自己独特的接口和方法集相比,有没有什么主要优势。
例如:一个通用的IRepository接口可能类似于(取自this answer):
public interface IRepository : IDisposable
{
T[] GetAll<T>();
T[] GetAll<T>(Expression<Func<T, bool>> filter);
T GetSingle<T>(Expression<Func<T, bool>> filter);
T GetSingle<T>(Expression<Func<T, bool>> filter, List<Expression<Func<T, object>>> subSelectors);
void Delete<T>(T entity);
void Add<T>(T entity);
int SaveChanges();
DbTransaction BeginTransaction();
}
每个存储库都将实现此接口,例如:
我们在以前的项目中遵循的备选方案是:
public interface IInvoiceRepository : IDisposable
{
EntityCollection<InvoiceEntity> GetAllInvoices(int accountId);
EntityCollection<InvoiceEntity> GetAllInvoices(DateTime theDate);
InvoiceEntity GetSingleInvoice(int id, bool doFetchRelated);
InvoiceEntity GetSingleInvoice(DateTime invoiceDate, int accountId); //unique
InvoiceEntity CreateInvoice();
InvoiceLineEntity CreateInvoiceLine();
void SaveChanges(InvoiceEntity); //handles inserts or updates
void DeleteInvoice(InvoiceEntity);
void DeleteInvoiceLine(InvoiceLineEntity);
}
在第二种情况下,表达式(LINQ或其他)将完全包含在存储库实现中,任何实现服务的人只需要知道要调用哪个存储库函数。
我想我看不到在服务类中编写所有表达式语法并将其传递给存储库的好处。这不是意味着在许多情况下,易于使用的LINQ代码正在被复制吗?
例如,在我们的旧发票系统中,我们调用
InvoiceRepository.GetSingleInvoice(DateTime invoiceDate, int accountId)
来自一些不同的服务(客户、发票、账户等)。这似乎比在多个地方编写以下代码要干净得多:
rep.GetSingle(x => x.AccountId = someId && x.InvoiceDate = someDate.Date);
我看到使用特定方法的唯一缺点是,我们最终可能会得到许多Get*函数的排列,但这似乎仍然比将表达式逻辑推入服务类更可取。
我遗漏了什么?
https://stackoverflow.com/questions/1230571
复制相似问题