我有一个通用的存储库接口(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/