public async Task Execute <TIdent>(IEventStoreAsync eventStorage, TIdent id, Action <TAggregateRoot> execute) where TIdent : IIdentity { if (eventStorage == null) { throw new ArgumentNullException("eventStorage"); } if (id == null || id.Equals(default(TIdent))) { throw new ArgumentException("id is null or default value", "id"); } // Load event stream from the store var stream = await eventStorage.LoadEventStream(id); // create new Customer aggregate from the history var aggregate = new TAggregateRoot(); aggregate.LoadsFromHistory(stream.Events); // execute delegated action Logger.DebugFormat("Executing Update on aggregate {0}", aggregate); execute(aggregate); // append resulting changes to the stream, expect the same version loaded before applying ddd logic if (aggregate.Changes.Any()) { Logger.DebugFormat("Saving {0} uncommited events on aggregate {1}", aggregate.Changes.Count, aggregate); await eventStorage.AppendToStream(id, stream.Version, aggregate.Changes); } Logger.DebugFormat("Finished Update on {0}", aggregate); }
public async Task Execute <TIdent, TResult, TIdentCreated>(IEventStoreAsync eventStorage, TIdent id, Func <TResult, TAggregateRoot> execute, TIdentCreated createId) where TIdent : IIdentity where TResult : IAggregate, new() where TIdentCreated : IIdentity { if (eventStorage == null) { throw new ArgumentNullException("eventStorage"); } if (id == null || id.Equals(default(TIdent))) { throw new ArgumentException("id is null or default value", "id"); } if (createId == null || createId.Equals(default(TIdentCreated))) { throw new ArgumentException("createid is null or default value", "createId"); } EventStream stream = await eventStorage.LoadEventStream(id); // create new Customer aggregate from the history var aggregate = new TResult(); aggregate.LoadsFromHistory(stream.Events); // execute delegated action Logger.DebugFormat("Executing UpdateAndCreateAggregate on aggregate {0}", aggregate); TAggregateRoot res = execute(aggregate); if (aggregate.Changes.Any()) { throw new Exception("You cannot modify more than one aggregate per command!"); } if (res != null && res.Changes.Any()) { Logger.DebugFormat("Saving {0} uncommited events on result aggregate {1}", res.Changes.Count, res); await eventStorage.AppendToStream(createId, 0, res.Changes); Logger.DebugFormat("Finished Create on {0}", aggregate); return; } throw new InvalidOperationException("No aggregate created on execute"); }