我現在正在學習由Jeffrey Palermo開發的Onion Architecture超過2周。我已按照this tutorial創建了一個測試項目。在學習期間,我遇到了關於SO的this問題。根據接受的答案,一個人nwang
建議像GetProductsByCategoryId這樣的方法不應該在存儲庫中,另一方面Dennis Traub
表明它是存儲庫的責任。我做的是:洋蔥體系結構 - 服務層責任
我有一個通用存儲庫中Domain.Interface
中,我有一個方法Find
:
public interface IRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> filter = null);
.......
.......
.......
}
然後,我創建了一個BaseRepository
在Infrastucture.Data
:
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();
}
}
而且我有a 混凝土存儲庫 in 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();' – sunil
是的,我在很多例子中看到了這種方法,但是你的工作單元將成爲存儲庫容器與所有存儲庫緊密耦合到工作單元。 –
存儲庫與工作單元的一個美麗的例子是在這裏:http://www.codeproject.com/Articles/543810/Dependency-Injection-and-Unit-Of-Work-using-Castle –