[英]MVC design pattern, service layer purpose?
假設我有以下回購模式:
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
?
服務層是否應該與我的 repo 1:1 映射?
我已經環顧了幾天,但我對答案並不滿意。
任何幫助將不勝感激,並為糟糕的英語道歉。
謝謝你。
更新 :
我已經讀過這個了。 我已經知道這兩個之間的區別,但我想知道原因和目的。 所以這不能回答我的問題
TL; 博士
解釋
典型的三層架構由表示層、服務/域層、數據訪問層(DAL)組成。
將服務層視為應用程序的“核心”。 通常,服務層只有將在 DAL 中實現的存儲庫接口。
因此,它允許您“輕松”切換訪問數據的方式。 服務層返回的對象不應該是 DAO,因為畢竟表示層甚至“不知道”DAL 的存在。
場景:您有一個 3 層解決方案。 目前擁有所有層沒有多大意義。
/-------------------\
| Web App | <--- Presentation Layer
|-------------------|
| Service Library | <--- Service Layer
|-------------------|
| Entity Framework | <--- Data Access
\-------------------/
現在你想在 ASP.NET MVC WebApi 中有一個 REST API
/--------------------\
| Web App | REST API | <--- Presentation Layer
|--------------------|
| Service Library | <--- Service Layer
|--------------------|
| Entity Framework | <--- Data Access
\--------------------/
現在,例如,您不再希望使用實體框架作為您的數據訪問,而希望使用 NHibernate。
/--------------------\
| Web App | REST API | <--- Presentation Layer
|--------------------|
| Service Library | <--- Service Layer
|--------------------|
| NHibernate | <--- Data Access
\--------------------/
請注意,我們添加了一種新的 Presentation 形式並切換了訪問數據的方式,但服務層從未改變。
通常,服務層公開要在數據訪問層中實現的接口,以便我們獲得我們想要的“抽象”。
我在大學里用這種架構實現了一個項目。 您可以在此處查看代碼
我希望這有幫助。 對不起,如果我很無聊@解釋事情:P
Ad.1 服務層應該是整個業務邏輯的地方。 更多的是關於單獨的職責:
控制器 - 負責准備 viewModel 並傳遞給特定的視圖,
Repository - 負責從 DB 收集實體的抽象層
服務——負責復雜的邏輯。 通常情況下,服務使用許多實體來制作一些邏輯並僅返回 DTO。
Ad.2 在我看來,服務層應該返回 DTO 對象,這些對象應該映射到控制器中的視圖模型。
Ad.3 不,情況並非如此。 在您的示例中,您可以將 GetBadCust 和 GetGoodCust 從 repo 移動到服務並返回一些 DTO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.