Reputation: 8481
I have been to told here that I should separate my Service
class and Repository
class, so I did. And below is an example.
public class ProductService
{
private readonly IProductRepository productRepository;
public ProductService(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public IEnumerable<Product> GetCurrentProductsOnOrderForCustomer(int customerId)
{
// etc.
}
}
But how do I use this in my Controller
? How I use it is like this:
public class ProductController : Controller
{
ProductService prodService = new ProductService();
}
But I've read that should implement abstraction. Should I make another class called IProductService
and use it like this?
public class ProductController : Controller
{
private readonly IProductService _productService;
private readonly IUnitOfWork _uow;
public ProductController(IProductService productService, IUnitOfWork uow)
{
_uow = uow;
_productService = productService;
}
}
An example of IProductService
would be great. Any help would be much appreciated. Thanks.
Upvotes: 0
Views: 624
Reputation: 913
You should write your different layers like this:
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.
}
}
So the controller layer should do this:
public class ProductController : Controller
{
private readonly IProductService prodService;
public ProductController(IProductService prodService)
{
this.prodService = prodService;
}
}
And your webapp layer, should use Dependency Injection to fill the different constructors. Or you can do it manually in case of a small business domain.
Upvotes: 1