c# - 存储库和服务层交互问题

标签 c# domain-driven-design service repository-pattern

我有一个通用的存储库接口(interface),它具有从服务层保存、读取和查询的常用方法,如下所示:

public interface IRepository<T>
{
    T GetById(int id);
    void Save(T entity);
    void Update(T entity);
    void Delete(T entity);
    IEnumerable<T> GetAll();
}

如果我有一项服务,例如使用 IRepository 的具体实现的用户服务与 User作为它的类型( IRepository<User> ),如果服务本身可能需要来自另一个 IRepository 的东西说 IRepository<Admin>服务是否应调用 IRepository<Admin>直接调用,还是应该调用关联服务(即主要处理 IRepository<Admin> 存储库的服务)?

如果你直接从存储库中提取项目,我个人会看到一个问题,如果你想在结果返回给客户端之前应用某些业务规则,但另一方面,服务可能想要处理原始结果集并将其自己的规则应用于结果,所以我对采取哪个方向有点困惑,任何建议将不胜感激。

最佳答案

如果所有存储库的实现细节都相同,您可能会创建一个抽象的 BaseRepository,例如:

protected abstract class BaseRepo<T> : IRepository<T>
     where T : class
{
    #region IRepository Members

    // Implement all IRepository members here and make them public

    #endregion
}

然后您可以创建一个专用的 AdminRepository,例如:

public class AdminRepo : BaseRepo<Admin> {}

要从另一个存储库调用,您可以执行以下操作:

public class UserRepo : BaseRepo<User>
{
    private AdminRepo adminRepo = new AdminRepo();

    public UserRepo()
    {
        Admin person = adminRepo.GetById(1);
    }
}

希望对您有所帮助。

关于c# - 存储库和服务层交互问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4859617/

相关文章:

c# - Visual Studio 中的输出窗口没有调试选项

c# - String.IsNullOrEmpty 未检测到 C# 中的转义序列 NULL\0

domain-driven-design - 洋葱架构中的资源文件放在哪里?

java - 如何建模两个聚合根之间的关系

php - 如何每 500 毫秒在 linux 中执行一次代码?

c# - 在 C# 中闭包不是不可变的有什么充分的理由吗?

c# - 导出非托管函数指针时发生访问冲突

architecture - DDD-每个实体的存储库还是所有实体的存储库?

java - spring mvc中生成文件流程更新

linux - 在超过 StartLimitBurst 后启动 linux 服务的解决方法