Good time of day. Faced with a strange situation. I am studying the well-known Jason Taylor template by many (github)
public class CreateTodoItemCommandHandler : IRequestHandler<CreateTodoItemCommand, int>
{
private readonly IApplicationDbContext _context;
public CreateTodoItemCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<int> Handle(CreateTodoItemCommand request, CancellationToken cancellationToken)
{
var entity = new TodoItem
{
ListId = request.ListId,
Title = request.Title,
Done = false
};
entity.AddDomainEvent(new TodoItemCreatedEvent(entity));
_context.TodoItems.Add(entity);
await _context.SaveChangesAsync(cancellationToken);
return entity.Id;
}
}
An event is added here, then a new TodoItem object is added to the database, and then SaveChangesAsync() is called.
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
await _mediator.DispatchDomainEvents(this);
return await base.SaveChangesAsync(cancellationToken);
}
This code calls notifies subscribers and only then calls SaveChangesAsync(). What if listeners receive a notification, but SaveChangesAsync() fails? W̶h̶y̶ ̶t̶h̶i̶s̶ ̶p̶a̶r̶t̶i̶c̶u̶l̶a̶r̶ ̶o̶r̶d̶e̶r̶ ̶o̶f̶ ̶o̶p̶e̶r̶a̶t̶i̶o̶n̶s̶?̶ Do you agree with me that the order of operations should be different?