ASP.NET服务VS库层 [英] ASP.NET service vs repository layers

查看:101
本文介绍了ASP.NET服务VS库层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是一个服务层和存储库之间的区别?我已经经历了很多演示ASP.NET MVC应用程序的工作,他们大多刚刚库。而一些有两者的混合。如果你只使用存储库和你什么时候使用服务/或两者兼而有之?同样是真实的ASP.NET Web应用程序。

What is the difference between a service layer and a repository? I have worked through a lot of demo ASP.NET MVC apps and most of them have just repositories. And some have a mixture of both. When do you use just repositories and when do you use services / or both? The same is true for ASP.NET web apps.

推荐答案

库行动就像网关您的数据存储(SQL数据库,XML文件等),而服务通常发送数据之前实现对数据的一些业务规则经由存储库被保存在数据库中。

Repositories act just as gateways to your data storage (sql database, xml file etc.) while services usually implement some business rules on your data before sending the data to be saved in the database via a repository.

考虑这个例子:

class UserRepository : IUserRepository
{
   public void Create(User userToCreate)
   {
       //update tracking and save to repository
       _userToCreate.DateCreated = DateTime.Now;
       _dataContext.AddNew(userToCreate);
   }
}


class UserService : IUserService 
{
   private IUserRepository _repository;

   public UserService(IUserRepository repository)
   {
        _repository = repository;
   }

   public void Create(User createdByUser, User userToCreate)
   {
       //implement some business rules
       if(!createdByUser.HasRights(UserRights.CanCreateNewUser))
           throw new Exception("This user '"+createdByUser.Name+"' does not have the rights to create a new user");

       //update rules auditing
       _userToCreate.CreatedByUserId = createdByUser.Id;

       //save entity to repository
       _repository.Create(userToCreate);
   }
}

然后在你的控制器动作,你将直接使用该服务可以应用所有的业务规则。你可以测试你的控制器,业务规则(服务)和持久性(资料库),这样分开/独立使用嘲笑。

Then in your Controller action you will use the service directly where all your business rules can be applied. That way you can test you controllers, business rules (services) and persistence (repositories) separately/independently using mocks.

    public ActionResult CreateUser(User newUser)
    {
        if(ModelState.IsValid)
        {
           _userService.Create(this.CurrentUser, newUser);
           if(newUser.Id > 0)
               return RedirectToAction("UserCreated");
        }
        return View(newUser);
    }

这篇关于ASP.NET服务VS库层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆