MVC3 Design - repository pattern and services layer [closed]

隐身守侯 提交于 2019-12-04 12:02:41

问题


I have read a couple of books and articles on MVC, and come across the repository pattern and the services layer.

Should a controller be able to get entities through the repository pattern, or must it retrieve data from the services layer?

Edit: I have code in the services layer that looks like this

public UserInfo GetModel(int userInfoID)
{
    return userInfoRepo.Get(userInfoID);
}

public UserInfo GetUserByPortalID(string portalID)
{
    return userInfoRepo.GetByPortalID(portalID);
}

public UserInfo GetModelByUserName(string username)
{
    return userInfoRepo.GetByUserName(username);
}

If a method in a service only calls another method in repository, is it necessary to have the controller go through the service?


回答1:


In layered application architecture there's a fundamental rule that says that you must never bypass a layer. If you query your repository straight from your controller, you would be violating that rule.

So what? you may say. What if the service layer adds no value? Well, it might in the future...

You can choose to break the rule, but then it wouldn't be a layered application any more. That may be okay too - there are other good (even better) application architectures available, but I think that first you should make a decision regarding the overall architecture, and then you stick with that decision. Otherwise you'll end up with spaghetti code - we call it lasagna when it's a layered application :)




回答2:


It depends. If you plan to have complex bussiness rules in the future I would add the service layer. If your site only does CRUD operations with little or no logic in the service layer you could directly call you repository layer.




回答3:


Should a controller be able to get entities through the repository pattern, or must it retrieve data from the services layer.

Ideally the controller should use only the service layer which itself depends on one or more repositories in order to aggregate one or more simple CRUD operations into a business operation. There are cases though in simple applications where you might not need a service layer and have the controller directly use a repository.




回答4:


It's always a question what suits your better and what your style is. As for me, I prefer accessing service layer from controller action. The service will then access the repository model.

public class UserController : MyServiceController<UserServices>
{
    public ActionResult GetUser(int id)
    {
        var user = Service.GetUser(id);
        return View(user);
    }
}

public class UserServices : MyServices<User>
{
    public User GetUser(int userId)
    {
        return Repository.Single(a=>a.Id == userId);
    }
}


来源:https://stackoverflow.com/questions/5645013/mvc3-design-repository-pattern-and-services-layer

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