0
votes

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?

Why are you asking the Stack Overflow community? It sounds like that's a question for the template author on GitHub. - David L
@DavidL I wanted to make sure I wasn't the only one with that opinion. I thought the answer from the author would take a long time. - Mauz
I would agree with you, but your question is specifically asking "why this particular order of operations", which only the author can answer for you. - David L
@DavidL Ohh.. I apologize for the incorrect wording. I'll fix it - Mauz