dotnet --version
dotnet add package MediatR
Separate commands (writes) from queries (reads) using MediatR, with distinct models for each side.
1 using MediatR; 2 3 namespace Application.Orders.Commands; 4 5 public record CreateOrderCommand( 6 Guid CustomerId, 7 List<OrderLineItem> Items 8 ) : IRequest<Guid>; 9 10 public record OrderLineItem(Guid ProductId, int Quantity, decimal UnitPrice); 11 12 public class CreateOrderCommandHandler : IRequestHandler<CreateOrderCommand, Guid> 13 { 14 private readonly IOrderRepository _orderRepo; 15 16 public CreateOrderCommandHandler(IOrderRepository orderRepo) 17 { 18 _orderRepo = orderRepo; 19 } 20 21 public async Task<Guid> Handle(CreateOrderCommand request, CancellationToken cancellationToken) 22 { 23 var total = request.Items.Sum(i => i.Quantity * i.UnitPrice); 24 var order = Order.Create(request.CustomerId, request.Items, total); 25 26 await _orderRepo.AddAsync(order, cancellationToken); 27 await _orderRepo.SaveChangesAsync(cancellationToken); 28 29 return order.Id; 30 } 31 } 32
Sign in to share your feedback and join the discussion.