Should i use service or repository in cqrs handler?

443 Views Asked by At

I have a project where I use mediatr, CQRS and onion architecture.

public class CreateOrderCommandHandler : IRequestHandler<CreateOrderCommand, CreatedOrderDto>
{
    private readonly IOrderRepository _orderRepository;
    private readonly IProductRepository _productRepository;
    private readonly IMapper _mapper;

    public CreateOrderCommandHandler(IOrderRepository orderRepository,IProductRepository 
                                     productRepository,  IMapper mapper)
    {
        _orderRepository = orderRepository;
        _productRepository = productRepository;
        _mapper = mapper;  
    }

    public async Task<CreatedOrderDto> Handle(CreateOrderCommand request, CancellationToken 
                                            cancellationToken)
    {
        // _orderRepository.Add(order);
        // _ productRepository.Update(product);
    }

}

Should CreateOrder Command depend on Product Service instead of ProductRepository?

Should the repository be used in the Handler?

1

There are 1 best solutions below

0
Vivek Nuna On

As per your code in the question, it should depend on ProductRepository not on the service, and service is a collection of classes while Reposiriry represents a single class so you cannot inject a service but you can inject a repository.

and by the way, I cannot see any Product Service in your code.