您能否提供一個帶有基本體系結構指導的代碼示例,用於創建服務層類(應該由web前端,web api等使用)?ASP.NET MVC應用程序最佳實踐中的服務層類
你認爲這是一個很好的教程嗎? http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs
您能否提供一個帶有基本體系結構指導的代碼示例,用於創建服務層類(應該由web前端,web api等使用)?ASP.NET MVC應用程序最佳實踐中的服務層類
你認爲這是一個很好的教程嗎? http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs
我個人不喜歡該文章描述瞭如何從服務層傳球失誤回控制器(帶IValidationDictionary),我會讓工作更是這樣,而不是:
[Authorize]
public class AccountController : Controller
{
private readonly IMembershipService membershipService;
// service initialization is handled by IoC container
public AccountController(IMembershipService membershipService)
{
this.membershipService = membershipService;
}
// .. some other stuff ..
[AllowAnonymous, HttpPost]
public ActionResult Register(RegisterModel model)
{
if (this.ModelSteate.IsValid)
{
var result = this.membershipService.CreateUser(
model.UserName, model.Password, model.Email, isApproved: true
);
if (result.Success)
{
FormsAuthentication.SetAuthCookie(
model.UserName, createPersistentCookie: false
);
return this.RedirectToAction("Index", "Home");
}
result.Errors.CopyTo(this.ModelState);
}
return this.View();
}
}
或..就像mikalai提到的那樣,使服務拋出驗證異常,在全局過濾器中捕獲它們並插入模型狀態。
或者,如果服務在使用過濾器處理的錯誤上拋出異常,則可能會減少編碼。 – mikalai
mikalai,對! –
無關緊要,您正在使用MVC 4.它與MVC 3和MVC 2的工作方式相同。EF也是如此。只需使用Google,StackOverflow上就有數百個關於此主題的線程。 –
@Lean,是啊,這個主題上有數百個垃圾代碼示例:)例如,當沒有任何好理由的人在EF DbContext上實現自定義存儲庫和工作單元模式時,已經實現了這兩種模式。 –