要在更多的細節上Russ' great answer擴大,這樣考慮:
public class CheckoutController
{
private readonly ICommandHandler<CheckoutCommand> _checkoutHandler;
public CheckoutController(ICommandHandler<CheckoutCommand> checkoutHandler)
{
_checkoutHandler = checkoutHandler;
}
[HttpPost]
public virtual ActionResult Post(CheckoutViewModel viewModel)
{
if (!ModelState.IsValid) return View(viewModel);
var command = Mapper.Map<CheckoutCommand>(viewModel);
_checkoutHandler.Handle(command);
return RedirectToAction("Complete");
}
public virtual ActionResult Complete()
{
return View();
}
}
控制器沒有做任何事情businessy可言。它爲用戶提供控制流程。現在,考慮你有這樣的相關性注入到控制器:
public class DomainCheckoutCommandHandler : ICommandHandler<CheckoutCommand>
{
private readonly IEntityDataStorage _repos;
private readonly IEmailSender _email;
private readonly ILogger _log;
public DomainCheckoutCommandHandler(IEntityDataStorage repos,
IEmailSender email, ILogger log)
{
_repos = repos;
_email = email;
_log = log;
}
public void Handle(CheckoutCommand command)
{
// use _repos to Add an entry to a database table
// use _email to issue the receipt
// use _log to log the purchase
}
}
有關於使用thesethreeposts接口+ DI這樣一些偉大的信息。
最好的部分是您可以將MVC項目之外的所有其他代碼 - 接口,域類和其他接口實現 - 全部移出。這樣,MVC項目中沒有任何事情做任何事情。它只是委託給由業務層或其他類庫實現的接口。
這就是所有與模型有關的東西,所以它絕對是模型層。但這並不意味着它應該成爲購物車類的一部分。您可能需要CartWriter或CartReader來處理購物車在數據庫中的存儲(或可能在其他地方)。 – 2012-07-13 21:33:46