【问题标题】:usage of service layer classes as composition rather than inheritance使用服务层类作为组合而不是继承
【发布时间】:2014-06-27 15:56:07
【问题描述】:

有人告诉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 的示例会很棒。任何帮助将非常感激。谢谢。

【问题讨论】:

  • 我认为这个想法是将 UoW 注入到 Service 中,这样你就没有它在控制器上,并且构造函数应该是这样的:ProductController(IProductService service) 和 ProductService(IUow uow)。请记住,在使用 EF 时,UoW 可能不是一个很好的选择。
  • @Bart 嗨。谢了哥们。认为您将其与代码一起放入答案部分?以及为什么 UoW 不是 EF 的一个很好的选择。我想听听一些想法。谢谢。你看我是这个领域的新手。
  • 抱歉来晚了,我会指出一篇关于我对EF和UOW的担忧的好文章。还有更多,但如果您有兴趣,这是一个很好的第一次查找:tech.pro/blog/1191/say-no-to-the-repository-pattern-in-your-dal

标签: c# asp.net-mvc architecture


【解决方案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 层,应该使用依赖注入来填充不同的构造函数。或者,如果是小型企业域,您可以手动完成。

【讨论】:

猜你喜欢
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多