How to pass complex ViewModel to Service Layer in ASP.NET MVC?

雨燕双飞 提交于 2019-12-03 18:53:19

问题


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);
        }

Given that RegisterModel might be very complex, where is the logic should go for mapping RegisterModel to User object


回答1:


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.



来源:https://stackoverflow.com/questions/5053248/how-to-pass-complex-viewmodel-to-service-layer-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!