C# 4.0 访问多个表的存储库

C# 4.0 访问多个表的存储库,c#-4.0,architecture,service,repository-pattern,C# 4.0,Architecture,Service,Repository Pattern,此模型经过简化,仅用于演示。 在我的申请中: 资料 存储库 公共接口IRepository T:在哪里上课 { T添加(T实体); T移除(T实体); IQueryable GetAll(); int Save(); } 公共类ProductRepository:IRepository { 公共产品添加(产品实体){…} 公共产品删除(产品实体){…} 公共IQueryable GetAll(){…} public int Save(){…} } 公共类类别存储:IRepository { 公共

此模型经过简化,仅用于演示。

在我的申请中:

资料 存储库
公共接口IRepository
T:在哪里上课
{
T添加(T实体);
T移除(T实体);
IQueryable GetAll();
int Save();
}
公共类ProductRepository:IRepository
{
公共产品添加(产品实体){…}
公共产品删除(产品实体){…}
公共IQueryable GetAll(){…}
public int Save(){…}
}
公共类类别存储:IRepository
{
公共类别添加(类别实体){…}
公共类别删除(类别实体){…}
公共IQueryable GetAll(){…}
public int Save(){…}
}
服务 公共接口ICategoryService { 类别添加(产品、类别); } 公共类CategoryService:ICategoryService { 公共类别添加(Guid gidProduct,Category Category){…}//此处有问题 只读存储库; public CategoryService(IRepository repository)//此处存在问题 { _存储库=存储库; } } 当我需要从我的服务中的另一个存储库中获取信息时,每个类都有一个存储库,我应该怎么做

在上面的示例中,在我的服务层中,我有一个方法来添加一个产品(在那里我找到了它的代码)和一个类别


问题是我在产品存储库中进行搜索以恢复它,但在我的服务类类别中,没有产品存储库。,如何解决此问题?

首先,您需要为每个聚合根创建存储库,而不是为每个类创建存储库

如果您需要访问服务中的多个存储库,只需依赖所有存储库,就可以将它们作为参数添加到构造函数中以进行依赖项注入

public CategoryService(CategoryRepository  categoryRepository, ProductRepository productRepository) 
{
    _categoryRepository = categoryRepository;
    _productRepository = productRepository;
}
public interface IRepository<T>
    where T : class
{
    T Add(T entity);
    T Remove(T entity);
    IQueryable<T> GetAll();
    int Save();
}

public class ProductRepository : IRepository<Product>
{
    public Product Add(Product entity) { ... }
    public Product Remove(Product entity) { ... }
    public IQueryable<Product> GetAll() { ... }
    public int Save() { ... }
}

public class CategoryRepository : IRepository<Category>
{
    public Category Add(Category entity) { ... }
    public Category Remove(Category entity) { ... }
    public IQueryable<Category> GetAll() { ... }
    public int Save() { ... }
}
public interface ICategoryService
{
    Category Add(Guid gidProduct, Category category);
}

public class CategoryService : ICategoryService
{
    public Category Add(Guid gidProduct, Category category){ ... } //Problem here

    readonly IRepository<Category> _repository;

    public CategoryService(IRepository<Category> repository)  //Problem here
    {
        _repository = repository;
    }
}
public CategoryService(CategoryRepository  categoryRepository, ProductRepository productRepository) 
{
    _categoryRepository = categoryRepository;
    _productRepository = productRepository;
}