public async Task DispatchAsync(ICommand <TEntity> command) { // Retreive events IEnumerable <IEvent> events = await EventStore.GetEventsAsync(command.Id); // Apply events to hydrate the aggregate Aggregate.ApplyEvents(events); // Handle the command events = Aggregate.HandleCommand(command); if (events.Nada()) { return; } // Persist the events if there were no failed. if (!events.Any(e => e.GetType() == typeof(Failed))) { var persisted = await EventStore.PersistEventsAsync(events); if (!persisted) { events = new IEvent[] { new Failed("Failed to persist events.") }; } } else { events = events.Where(e => e.GetType() == typeof(Failed)); } // Forward resulting events await EventMessenger.SendAsync(events); }
protected async Task Execute(Func <Task> function) { try { await function(); } catch (Exception ex) { //if exception ocurs while executing the command, we want to rollback any events that may have been added where the action wasn't successful Aggregate.PopNewEvents(); throw; } var newEvents = Aggregate.PopNewEvents(); if (newEvents.Count > 0) { //store in event store Aggregate.ApplyEvents(newEvents); //create snapshot } }