Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 存储库和服务层交互问题_C#_Domain Driven Design_Service_Repository Pattern - Fatal编程技术网

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

C# 存储库和服务层交互问题,c#,domain-driven-design,service,repository-pattern,C#,Domain Driven Design,Service,Repository Pattern,我有一个通用的存储库接口,它具有从服务层保存、读取和查询的常用方法,如下所示: public interface IRepository<T> { T GetById(int id); void Save(T entity); void Update(T entity); void Delete(T entity); IEnumerable<T> GetAll(); } 公共接口IRepository { T GetById(in

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

public interface IRepository<T>
{
    T GetById(int id);
    void Save(T entity);
    void Update(T entity);
    void Delete(T entity);
    IEnumerable<T> GetAll();
}
公共接口IRepository
{
T GetById(int-id);
无效保存(T实体);
无效更新(T实体);
无效删除(T实体);
IEnumerable GetAll();
}
如果我有一个服务,例如一个用户服务,它使用
IRepository
的具体实现,类型为
User
IRepository
),如果服务本身可能需要另一个
IRepository
的东西,比如说
IRepository
,那么服务应该直接调用
IRepository
,或者它应该调用关联的服务(即,主要处理
IRepository
存储库的服务)


我个人认为,如果您直接从存储库中提取项目,如果您想在结果返回到客户端之前应用某些业务规则,但另一方面,服务可能希望处理原始结果集,并将其自身的规则应用于结果,那么我有点困惑应该采取哪种方向,如果所有存储库的实现细节相同,您可能会创建一个抽象的BaseRepository,例如:

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

    // Implement all IRepository members here and make them public

    #endregion
}
public class AdminRepo : BaseRepo<Admin> {}
受保护的抽象类BaseRepo:IRepository
T:在哪里上课
{
#地区成员
//在此处实施所有IRepository成员并将其公开
#端区
}
然后,您可以创建一个专用的AdminRepository,例如:

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

    // Implement all IRepository members here and make them public

    #endregion
}
public class AdminRepo : BaseRepo<Admin> {}
public类AdminRepo:BaseRepo{}
要从另一个存储库调用,可以执行以下操作:

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

    public UserRepo()
    {
        Admin person = adminRepo.GetById(1);
    }
}
公共类UserRepo:BaseRepo
{
private AdminRepo AdminRepo=new AdminRepo();
公共用户repo()
{
Admin person=adminRepo.GetById(1);
}
}

希望这能有所帮助。

Raghu,我的问题不是如何实现存储库,而是给定服务调用多个存储库是否合适。绝对是这样。服务依赖于多个repo/facade是一种常见的场景。但是,如果您担心在服务中创建具体实例,您可以在运行时使用IoC conatiner注入存储库依赖项。让一个服务向您的客户提供与上下文相关的数据也将简化您的设计。干杯,我们使用结构图作为任何依赖项的IoC容器。