我们正在开发一个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();
}
每个存储库都将实现此接口,例如:
- CustomerRepository:IRepository
- ProductRepository:IRepository
- 等
我们在之前的项目中采用的替代方案是:
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*函数的排列,但这似乎比将表达式逻辑向上推到服务类中更可取.
我遗漏了什么?