假设我有以下回购模式:
interface IGenericRepo<T> where T : class
{
IEnumerable<T> GetAll();
T GetById(object id);
void Insert(T obj);
void Update(T obj);
void Delete(T obj);
void Save();
}
interface ICustRepo : IGenericRepo<Cust>
{
IEnumerable<Cust> GetBadCust();
IEnumerable<Cust> GetGoodCust();
}
public class CustRepo : ICustRepo<Cust>
{
//implement method here
}
然后在我的控制器中:
public class CustController
{
private ICustRepo _custRepo;
public CustController(ICustRepo custRepo)
{
_custRepo = custRepo;
}
public ActionResult Index()
{
var model = _custRepo.GetAll();
return View(model);
}
public ActionResult BadCust()
{
var model = _custRepo.GetBadCust();
return View(model);
}
}
基本上我的模式是这样的
View <-> Controller -> Repo -> EF -> SQL Server
但我看到很多人这样做
View <-> Controller -> Service -> Repo -> EF -> SQL Server
所以我的问题是:
为什么以及何时需要
service layer
?这不只是添加另一个不必要的层,因为已经实现了每个非泛型方法ICustRepo
?服务层应该返回吗?
DTO
或者我的ViewModel
?服务层应该与我的仓库1:1映射吗?
我环顾了几天,但我对答案并不满意。
任何帮助将不胜感激并为糟糕的英语道歉。
谢谢。
更新:
我已经读过了。我已经知道那些2之间的区别,但我想知道为什么和目的。所以这不回答我的问题