加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:14:59 所属栏目:百科 来源:网络整理
导读:我有一个通用的存储库接口,它具有从服务层保存,读取和查询的常用方法,如下所示: public interface IRepositoryT{ T GetById(int id); void Save(T entity); void Update(T entity); void Delete(T entity); IEnumerableT GetAll();} 如果我有一个服务,例如
我有一个通用的存储库接口,它具有从服务层保存,读取和查询的常用方法,如下所示:

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

希望有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读