Question

What is recommended architectural approach for defining dependencies in a service class ?

Is this OK, when another class, ex. OrderService has dependencies to repository class ex. CartRepository instead of CartService? Should I always create one repository and one service per domain object ?

public class CartService : ICartService
{
    private IBuyerRepository _buyerRepository;
    private ICartRepository _cartRepository;
    private IConfigService _configService;  
    private ISimpleDataService _simpleDataService;

    public CartService(IBuyerRepository buyerRepository,
                       ICartRepository cartRepository,
                       IConfigService configService)
    {
        _buyerRepository = buyerRepository;
        _cartRepository = cartRepository;
        _configService = configService;
    }

    public void Save(Cart cart)
    {
        _cartRepository.Save(cart); 
    }
}

OrderService file:

public class OrderService : IOrderService
{
    public OrderService(ICartRepository cartRepository)
    {

    }
}
Was it helpful?

Solution

Your implementation is good as a first step, and in a simple, not too big, domain.

A such implementation has avantages: While just one service per http resquest manages all the repositories it needs, there is no difficulty to manage the sql transaction to maintain integrity.

It has too disadvantages: You could write two times, or more, the same business rules... We all are lazy so it's a problem. But a major failure will come when someone, or you, 6 months later, will call the repository for the third time in its service implementation and forget a business rule... bye bye lovely domain...

My recommendation would be that a service just call its repository, and calls the other services that encapsulate their own logic, when needed. The only trick to remember is to propagate the transaction to avoid odd things to happen.

Hope it helps, Julien

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top