Search code examples
c#asp.net-mvcrepositorybusiness-logic-layer

Can business layer of one module directly access repository of another module?


I am having a 3 layer architecture.

1) C# MVC Application - UI layer

2) Business Layer - consisting of service interfaces and its implementation and repository interfaces

3) Data Access Layer - consisting of Repository interface implementation

The application is divided into different modules. A module is nothing but a C# class library. Each module has its own business layer and data access layer. There is loose coupling between the layers, so each layer accesses the other through interface only. To give you an example, here is how the application is stacked up

// UI layer
public class UserController: Controller 
{
   IUserService userService;
   IOrderService orderService;

   public UserController(IUserService userService, IOrderService orderService){
     this.userService = userService;
     this.orderService  = orderService;
   }
}

//Business layer - User module
public class UserService: IUserService
{
   IUserRepository userRepository;
   IOrderRepository orderRepository;

   public UserService(IUserRepository userRepository, IOrderRepository 
   orderRepository){
      this.userRepository = userRepository;

      //Should this be here or replaced by order service ?
      this.orderRepository = orderRepository;
   }
}

//Business layer - Order module
public class OrderService: IOrderService
{
   IOrderRepository orderRepository;

   public UserService(IOrderRepository orderRepository){
      this.orderRepository= orderRepository;
   }
}

//Data access layer - User module

public class UserRepository: IUserRepository {
}

//Data access layer - Order module

public class OrderRepository: IOrderRepository {
}

Is it OK for the User service to directly access the Order repository or should it have dependency on the Order service only ?


Solution

  • You are accessing IOrderRepository in UserService. Your question is whether this is correct approach, or it should ONLY access IUserRepository and call OrderService instead of IOrderRepository.

    IMO, any service may call any repository as per need. There is no 1 <-> 1 relation between Service and Repository.

    Repository provide you an access to data. If such access is necessary in multiple services, then multiple services can consume same Repository. This looks very clean and explainable.