【发布时间】:2013-06-30 19:27:54
【问题描述】:
我正在学习 Jeffrey Palermo 的 Onion Architecture 已经两个多星期了。我按照this tutorial 创建了一个测试项目。在学习时,我遇到了关于 SO 的this 问题。根据接受的答案,一个人 nwang 建议像 GetProductsByCategoryId 这样的方法不应该在 Repository 中,而另一方面 Dennis Traub
表明这是存储库的责任。我正在做的是:
我在Domain.Interface 中有一个通用存储库,其中有一个方法Find:
public interface IRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> filter = null);
.......
.......
.......
}
然后我在Infrastucture.Data 中创建了一个BaseRepository:
public class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class
{
internal readonly DbSet<TEntity> dbSet;
public virtual IEnumerable<TEntity> Find(
Expression<Func<TEntity, bool>> filter = null)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
return query.ToList();
}
}
我在Infrastructure.Data中有一个具体的存储库
public class ProductRepository : RepositoryBase<Product>, IProductRepository
{
public ProductRepository(MyDBContext context)
: base(context)
{
}
}
现在我在服务层中所做的是将存储库注入服务并调用Repository.Find 以获取GetProductsByCategoryId 之类的方法。喜欢:
public class ProductService : IProductService
{
private readonly IUnitOfWork _unitOfWork;
private readonly IProductRepository _productRepository;
public ProductService(IUnitOfWork unitOfWork, IProductRepository productRepository)
{
_unitOfWork = unitOfWork;
_productRepository = productRepository;
}
public IList<Product> GetProductsByCategoryId(int CategoryId)
{
// At the moment, My code is like this:
return _productRepository.Find(e => e.CategoryId == CategoryId).ToList();
// My confusion is here. Am I doing it right or I need to take this code to
// ProductRepository and call _productRepositoy.GetProductsByCategoryId(CategoryId) here instead.
// If I do this, then Service Layer will become more of a wrapper around repository. Isn't it?
// My question is : What exactly will be the responsibility of the Service Layer in Onion Architecture?
}
}
【问题讨论】:
-
好像有点不对劲。 UnitOfWork 应该包装您的所有存储库。因此,您对获取存储库的调用应类似于
_unitOfWork.ProductRepository.Find(e => e.CategoryId == CategoryId).ToList(); -
是的,我在许多示例中都看到了这种方法,但是您的工作单元将成为一个存储库容器,所有存储库都与工作单元紧密耦合。
-
一个带有工作单元的存储库的漂亮示例在这里:codeproject.com/Articles/543810/…
标签: asp.net-mvc design-patterns repository-pattern onion-architecture