Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 Service Layer - multiple repositories per service?

Say I have a one to many relationship in my database between orderstatus and orders. My view for creating an new order would need to have a dropdown of orderstatuses.

I have separate repositories for order and order status as well as seperate services for manipulating orders and order statuses. Something like:

public class OrderService : IOrderService
{
    private readonly IRepository<Order> _orderRepository; 
    public OrderService(IRepository<Order> orderRepository) {_orderRepository = orderRepository }
    public IEnumerable<Orders> GetAllOrders(){...}
}

public class OrderStatusService : IOrderStatusService
{
    private readonly IRepository<OrderStatus> _OrderStatusRepository; 
    public OrderStatusService(IRepository<OrderStatus> orderStatusRepository)  {_orderStatusRepository = orderStatusRepository }
    public IEnumerable<OrderStatus> GetAllOrderStatuses(){...}
}

My order controller has a reference to the OrderService, a bit like this:

public class OrderController : Controller
{
 private readonly IOrderService orderService;

What is the best way to do get a list of orderstatuses from the db?

1) Include a reference to both repositories in the OrderService and include a method that will return orderstatuses.

public class OrderService : IOrderService
{
    private readonly IRepository<Order> _OrderRepository; 
    private readonly IRepository<OrderStatus> _OrderStatusRepository;  ...

2) Make the controller aware of both services and use the GetOrderStatus method to get the list of OrderStatuses:

  public class OrderController : Controller
{
 private readonly IOrderService orderService;
 private readonly IOrderService orderStatusService; ...

3) Use the OrderStatusService from the OrderService to get the list of Order Statuses, something like:

    public class OrderService : IOrderService
{
    private readonly IRepository<Order> _orderRepository; 
    private readonly IOrderService _orderService; ...
    public IEnumerable<OrderStatus> GetOrderStatuses()
    { return _orderService.GetOrderStatuses; } ...

4) Another cool way that I cant think of :)

like image 464
woggles Avatar asked Jun 10 '11 09:06

woggles


1 Answers

Personally, I would go with your option #1 - combine your two existing services into one. Remember your service layer is supposed to act as a facade over lower level services like your repositories. Having two separate services for this kind of defeats the purpose.

like image 162
DanP Avatar answered Nov 10 '22 03:11

DanP