如何通过复杂的视图模型到服务层在ASP.NET MVC? [英] How to pass complex ViewModel to Service Layer in ASP.NET MVC?
问题描述
说我有RegisterModel的用户注册和一些UserService,实施IUserService
Say I have RegisterModel for user registration and some UserService that implementing IUserService
public interface IUserService
{
User CreateUser(User newUser);
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// ... logic for newuser
User user = _userService.CreateUser(newuser);
_authenticationService.SetAuthenticatedUser(user);
return RedirectToRoute("Homepage");
}
return View(model);
}
由于RegisterModel可能是非常复杂的,哪里是逻辑应该去映射RegisterModel到用户对象
Given that RegisterModel might be very complex, where is the logic should go for mapping RegisterModel to User object
推荐答案
您永远传递一个视图模型到服务。服务甚至不知道,你可能在你的GUI(ASP.NET MVC)层定义视图模型的存在。服务与域模型作品。我个人使用 AutoMapper 以视图模型和模型,反之亦然之间进行映射,所以这个逻辑进入映射层。
You never pass a view model to a service. A service doesn't even know about the existence of a view model that you might have defined in your GUI (ASP.NET MVC) tier. A service works with domain models. Personally I use AutoMapper to map between view models and models and vice versa, so this logic goes into the mapping layer.
这篇关于如何通过复杂的视图模型到服务层在ASP.NET MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!