使用服务层类作为组合而不是继承

时间:2014-06-26 02:44:20

标签: c# asp.net-mvc architecture

我已经告诉here我应该将Service班级和Repository班级分开,所以我做了。以下是一个例子。

public class ProductService
{
    private readonly IProductRepository productRepository;

    public ProductService(IProductRepository productRepository)
    {
        this.productRepository = productRepository;
    }

    public IEnumerable<Product> GetCurrentProductsOnOrderForCustomer(int customerId)
    {
        // etc.
    }
}

但我如何在Controller中使用此功能?我如何使用它是这样的:

public class ProductController : Controller
{
  ProductService prodService = new ProductService();
}

但我读过应该实现抽象。我应该创建另一个名为IProductService的类并像这样使用它吗?

public class ProductController : Controller
{
  private readonly IProductService  _productService;
  private readonly IUnitOfWork _uow;

  public ProductController(IProductService  productService, IUnitOfWork uow)
  {
    _uow = uow;
    _productService = productService;
  }
}

IProductService的一个例子会很棒。任何帮助将非常感激。感谢。

1 个答案:

答案 0 :(得分:1)

您应该像这样编写不同的图层:

public class ProductService : IProductService
{
    private readonly IProductRepository productRepository;

    private readonly IUnitOfWork unitOfWork;

    public ProductService(IProductRepository productRepository, IUnitOfWork unitOfWork)
    {
        this.productRepository = productRepository;
        this.unitOfWork = unitOfWork;
    }

    public IEnumerable<Product> GetCurrentProductsOnOrderForCustomer(int customerId)
    {
        // etc.
    }
}

所以控制器层应该这样做:

public class ProductController : Controller
{
     private readonly IProductService prodService;

     public ProductController(IProductService prodService)
     {
         this.prodService = prodService;
     }
}

您的webapp层应该使用依赖注入来填充不同的构造函数。或者,如果是小型企业域,您可以手动执行此操作。