public async override Task <AddGreetingCommand> HandleAsync(AddGreetingCommand command, CancellationToken cancellationToken = default(CancellationToken)) { await _unitOfWork.BeginTransactionAsync(cancellationToken); try { //Save the new Greeting var greeting = new Greeting() { GreetingMessage = command.GreetingMessage }; await _dataContext.GreetingsRegister.AddAsync(greeting, cancellationToken); //Create an Event for externals var newGreetingAddedEvent = new GreetingAsyncEvent() { Greeting = command.GreetingMessage }; var eventId = await _commandProcessor.DepositPostAsync(newGreetingAddedEvent, cancellationToken : cancellationToken); await _dataContext.SaveChangesAsync(cancellationToken); if (command.ThrowError) { throw new Exception("something broke error"); } else { //Ensure for Testing to Ensure that Contexts are not shared Thread.Sleep(5000); } await _unitOfWork.CommitAsync(cancellationToken); //In Case there is no outbox Sweeper await _commandProcessor.ClearOutboxAsync(new[] { eventId }, cancellationToken : cancellationToken); Console.WriteLine($"Message {command.GreetingMessage} Saved."); } catch (Exception e) { Console.WriteLine(e); await _unitOfWork.RollbackAsync(cancellationToken); Console.WriteLine($"Message {command.GreetingMessage} not Saved."); } return(await base.HandleAsync(command)); }
public async Task <IActionResult> SendMessage() { var greetingAsync = new GreetingAsyncEvent("Hello from the web"); var greeting = new GreetingEvent("Hello from the web"); _context.Greetings.Add(greeting); _context.GreetingsAsync.Add(greetingAsync); await _context.SaveChangesAsync(); _commandProcessor.Post(greeting); await _commandProcessor.PostAsync(greetingAsync); return(View("Index")); }
public async Task <IActionResult> SaveAndRollbackMessage() { var transaction = await _context.Database.BeginTransactionAsync(); // try // { var greetingAsync = new GreetingAsyncEvent("Hello from the web - 1"); var greeting = new GreetingEvent("Hello from the web - 1"); _context.Greetings.Add(greeting); _context.GreetingsAsync.Add(greetingAsync); await _context.SaveChangesAsync(); _commandProcessor.DepositPost(greeting); await _commandProcessor.DepositPostAsync(greetingAsync); //throw new Exception("Something went wrong"); // } // catch (Exception e) // { await transaction.RollbackAsync(); // } var greetingAsync2 = new GreetingAsyncEvent("Hello from the web - 2"); var greeting2 = new GreetingEvent("Hello from the web - 2"); _context.Greetings.Add(greeting2); _context.GreetingsAsync.Add(greetingAsync2); _commandProcessor.DepositPost(greeting2); await _context.SaveChangesAsync(); await _commandProcessor.DepositPostAsync(greetingAsync2); var msgs = new List <Guid>(); // msgs.Add(greeting.Id); // msgs.Add(greetingAsync.Id); msgs.Add(greeting2.Id); msgs.Add(greetingAsync2.Id); await _commandProcessor.ClearOutboxAsync(msgs); return(View("Index")); }