Model view controller NET MVC模式-如何在控制器中使用两个独立的存储库(使用DI)

Model view controller NET MVC模式-如何在控制器中使用两个独立的存储库(使用DI),model-view-controller,asp.net-mvc-2,design-patterns,Model View Controller,Asp.net Mvc 2,Design Patterns,我有两张非常简单的桌子。Product和ProductCategory(ProductCategory类似于产品的“查找”表)。在我的控制器上,对于Index()方法,我想列出产品的类别。当用户单击某个类别时,我希望将我的类别传递给my List()方法以显示特定类别的所有产品 我使用的是ninject DI框架;我现在有类似的东西 private IProductCategory productCategoryRepository; private IProduct productReposi

我有两张非常简单的桌子。Product和ProductCategory(ProductCategory类似于产品的“查找”表)。在我的控制器上,对于Index()方法,我想列出产品的类别。当用户单击某个类别时,我希望将我的类别传递给my List()方法以显示特定类别的所有产品

我使用的是ninject DI框架;我现在有类似的东西

private IProductCategory productCategoryRepository;
private IProduct productRepository;

public StoreController(IProductCategory productCategoryRepository)
{
    this.productCategoryRepository = productCategoryRepository;
}

public ViewResult Index()
{
    return View(productCategoryRepository.GetCategories());
}

  public ViewResult List(string category, int page = 1) //Use default value
  {
      ...
  };
我有每个表/实体的基本存储库(即GetCategories()、GetProducts()、GetProductsByCategority..等等)。最好的方法是什么…或者如何在控制器中使用两个独立的存储库?我不想让它们都通过控制器


注意:Product和ProductCategory不被视为聚合。

正如我前面提到的,服务层可以帮助您解决这个问题。服务层是用户界面和中间层之间的契约点。这可能是一个WCF服务,也可能是我在下面展示的一个简单的服务实现

public interface IMyProductService 
{
   IList<Product> GetProducts();
   IList<Product> GetProductsByCategory();
   IList<Category> GetCategories();
}

public class MyProductService : IMyProductService
{
   IProductRepository _prodRepo;
   IProductCategoryRepository _catRepo;

   public MyProductService(IProductRepository prodRepo, IProductCategoryRepository catRepo)
   {
      _prodRepo = prodRepo;
      _catRepo = catRepo;
   }

   // The rest of IMyProductService Implementation
}
公共接口IMyProductService
{
IList GetProducts();
IList GetProductsByCategory();
IList GetCategories();
}
公共类MyProductService:IMyProductService
{
IPProductRepository\u prodRepo;
i产品分类报告;
公共MyProductService(IPProductRepository prodRepo、IPProductCategoryRepository catRepo)
{
_prodRepo=prodRepo;
_catRepo=catRepo;
}
//IMyProductService实现的其余部分
}

您的MVC控制器将有一个对IMyProductService的引用,可能使用构造函数注入和您选择的DI框架。

考虑将您的存储库分组到服务中。服务作用于逻辑上协同工作/具有强大关联的回购协议。我不熟悉在MVC应用程序上下文中设计“服务”。你能提供一些关于设计它们的链接或信息吗?或者,您可以在上面的示例中给出一个如何实现服务的好例子作为答案:)