Example #1
0
        public virtual void Save(T aggregate, int expected_version)
        {
            var events = aggregate.GetUncommittedChanges().ToArray();

            int current_expected_version = expected_version;

            while (true)
            {
                try {
                    Save(aggregate.ID, events, current_expected_version);
                    break;
                } catch (AggregateException e) {
                    if (e.InnerException == null ||
                        !(e.InnerException is WrongExpectedVersionException))
                    {
                        throw;
                    }

                    IList <Event> events_since =
                        storage_.GetEventsForAggregateSince(aggregate.ID, serialzer_,
                                                            expected_version);

                    if (events_since.Count == 0)
                    {
                        throw new AggregateException("The current version is earlier than "
                                                     + " the expected.");
                    }

                    foreach (Event commited_event in events_since)
                    {
                        foreach (Event @event in events)
                        {
                            if (conflict_evaluator_.ConflictWith(commited_event, @event))
                            {
                                throw new ConcurrencyException();
                            }
                        }
                    }
                    current_expected_version = events_since.Last().Version;
                }
            }
        }