c# - MVC3 通过服务公开存储库功能

标签 c# asp.net-mvc-3

我一直在尝试使用 asp.net MVC3,并且一直在努力决定在哪里放置我的业务逻辑。我现在决定使用服务层:

    public class AnimalsService : IAnimalsService
    {
        private readonly IAnimalsRepository _animalsRepository;

        public AnimalsService(IAnimalsRepository animalsRepository)
        {
            _animalsRepository = animalsRepository;
        }
        public IQueryable<Animal> GetFiveLeggedAnimals()
        {
        ...
        }
    }

Controller 看起来像这样:

public class AnimalsController : Controller
{        
    private readonly IAnimalsService _animalsService;

    public AnimalsController(IAnimalsService animalsService)
    {
        _animalsService = animalsService;
    }

    public ViewResult ListFiveLeggedAnimals()
    {
        var animals = _animalsService.GetFiveLeggedAnimals();
        return View(animals);
    }
}

我在存储库中有基本的 CRUD 逻辑(全部、查找、更新或插入、删除)。如果我想在我的 Controller 中使用这些 CRUD 方法:

1) 我是否必须在服务中为这些存储库调用创建包装器方法?

2) 只在存储库中包含 GetFiveLeggedAnimals 方法和其他业务逻辑对我来说不是更有意义吗?

3) 我能否在 AnimalsService 中实现 IAnimalsRepository 接口(interface),然后调用基本方法(我意识到这是可能的,但我认为这是不好的做法)?

最佳答案

1) Do I have to create wrapper methods in the service for these respository calls?

大多数情况下,是的。通常,您希望为服务层中的域模型提供 CRUD。这样, Controller 就不需要直接与存储库一起工作(事实上,它永远不应该)。您可以稍后添加更多更复杂的逻辑,而无需更改外部代码。例如,假设您想实现一个新闻源。现在每次插入五足动物时,您都想创建一个新闻项并将其推送给五足动物的粉丝。另一个常见示例是电子邮件通知。

2) Would it not make more sense for me to just include the GetFiveLeggedAnimals method and other business logic in the repository?

业务逻辑应该位于服务层领域模型 对象本身中,并且只能存在于此。事实上(见 3),我不会专门提供 IAnimalRepository如果可能的话。

例如,在 NoSQL 环境中,数据库驱动程序几乎 是一个存储库。另一方面,当使用复杂的 ORM 映射和存储过程(其中部分业务逻辑在数据库中)时,您别无选择,只能提供了解存储过程的显式接口(interface)。

我会去 IRepository<T>并尽可能使用查询对象 模式。我认为 LINQ 也可以被视为基于查询对象/存储库 的模式。

3) Could I implement the IAnimalsRepository interface in the AnimalsService and then call the base methods (I realise this is possible but I assume its bad practice)?

要调用base 方法,您必须继承具体的实现,例如来自 ConcreteAnimalsRepository .

此外,如果您的服务实现了 IAnimalsRepository直接或间接接口(interface),它使(未过滤的)CRUD 操作可供所有人使用。

我的看法:不要继承,聚合。服务层一个存储库,但它不是本身是一个存储库:服务层处理所有额外的应用程序逻辑(权限、通知),而存储库是一个非常db 层周围的薄包装器。

举个极端的例子,如果禁止直接删除某物,只允许服务在插入某物的更新版本时使用它会怎样?这可以在聚合时轻松构建。

关于c# - MVC3 通过服务公开存储库功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6237409/

相关文章:

c# - 在编程中处理属性

c# - 已删除 用户在其他浏览器上删除后仍登录

c# - 如何使用 WebClient 登录站点?

c# - 由于 KeyNotFoundException,无法连接到 MySQL 数据库

c# - SQL 插入语句语法

asp.net-mvc - MVC 3 验证隐藏输入上的 htmlAttributes

c# - 识别字符串中的相似性

javascript - 嵌套 JSON 值不绑定(bind) MVC

c# - 在 Timer.Elapsed 事件上更新 MainWindow

c# - c# 中的链表和红/黑树 - 引用问题?