Beispiel #1
0
        protected void When <T>(
            Func <T, IDictionary <string, string>, string> getAggregateId,
            Func <TAggregate, T, IDictionary <string, string>, CancellationToken, Task> act,
            bool throwIfNotFound = true) where T : IMessage
        {
            _handlers.Add(typeof(T), async(message, headers, ct) =>
            {
                WrongExpectedStreamVersionException concurrencyException;
                do
                {
                    try
                    {
                        var aggregateId = getAggregateId((T)message, headers);

                        var aggregate = aggregateId == null
                            ? new TAggregate()
                            : await _repository
                                        .GetById <TAggregate>(aggregateId, ct)
                                        .ConfigureAwait(false);

                        if (throwIfNotFound && string.IsNullOrWhiteSpace(aggregate.Id))
                        {
                            throw new InvalidOperationException($"{typeof(TAggregate).Name} {aggregateId} not found!");
                        }

                        await act(aggregate, (T)message, headers, ct)
                        .ConfigureAwait(false);

                        await _repository
                        .Save(aggregate, headers, ct)
                        .ConfigureAwait(false);

                        concurrencyException = null;
                    }
                    catch (WrongExpectedStreamVersionException ex)
                    {
                        concurrencyException = ex;
                    }
                } while(concurrencyException != null);
            });
        }
 public static Task <TAggregate> GetById <TAggregate>(this AggregateRepository repository, string id, CancellationToken cancellationToken = default(CancellationToken))
     where TAggregate : IAggregateRoot, new() => repository.GetById <TAggregate>(id, int.MaxValue, cancellationToken);