我已经告诉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
的一个例子会很棒。任何帮助将非常感激。感谢。
答案 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层应该使用依赖注入来填充不同的构造函数。或者,如果是小型企业域,您可以手动执行此操作。