好吧,我想你的問題是,如何構建「層」在MVC應用程序。 看看這個簡單的架構,我將它用於我的MVC應用程序,它看起來乾淨而高效。
項目解決方案 - 商業模式 - 簡單的類庫充滿了代表業務領域的POCO類。您可以使用此數據註解,元數據類的驗證邏輯等
項目 - 基於EF-庫 - 另一個簡單的類庫;這裏定義的上下文(EF代碼首先是偉大的,但你可以先使用EF數據庫第一或模型 - 你只需要POCO T4模板添加到商業模式的類庫,沒什麼大不了的)和一組類 - 庫
項目 - 我通常稱之爲「ServiceLayer」左右(我打開的建議更好的名字:) - 它僅包含接口,倉庫和其他服務(在不同的項目中實現),將我的MVC(或任何其他技術)基於應用程序使用;從二,項目庫實現這些接口
項目 - MVC的網站。它使用依賴注入(構建在DependencyResolver中,我喜歡使用Ninject容器)來映射存儲庫(和其他服務);然後你可以使用構造器注入到控制器,或者一些「懶」的方法(見下文)
它看起來是這樣的:
瘦控制器:
public class SomethingController : BaseController
{
public ActionResult DoSomething(SomeBusinessThing input)
{
if (ModelState.IsValid)
{
var result = CustomerRepository.DoSomeBusinessLogicAndPersistenceAndStuff(input);
return View(result); // you can use AutoMapper here, if you dont want to use business object as viewmodels
}
}
}
我的倉庫「屬性「是繼承自我的BaseController:
public class BaseController : Controller
{
// ... other stuff used by all (or multiple) controllers
private ICustomerRepository _customerRepository;
protected ICustomerRepository CustomerRepository
{
get
{
if (_customerRepository== null)
_customerRepository= DependencyResolver.Current.GetService();
return _customerRepository;
}
}
}
如果您使用了」懶惰「控制器使用許多服務,但每個動作只有1-2個,因此將它們全部用構造函數注入將會是低效的。有人可以告訴你這樣「隱藏」依賴關係,但是如果你把所有這些東西放在一個地方 - BaseController,它沒什麼大不了的。
那麼,存儲庫的實施真的是你的業務。 MVC應用程序甚至不知道使用的是EF,它知道服務的唯一接口和犯規約墊層實施護理
Conslusion(你可以切換後,如果你需要的任何時間!):
這是一篇關於.NET應用程序體系結構的好書,並且有關於MVC的一節:http://www.amazon.com/Microsoft%C2%AE-NET-Architecting-Applications-Pro-Developer/dp/073562609X –