要在更多的细节上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