public async Task OnEventsDispatched_When_Defined_OnEventDispatched_Should_Not_BeCalled() { bool simpleCalled = false; bool multipleCalled = false; Func <IEnumerable <IDomainEvent>, Task> lambdaMulti = async(e) => multipleCalled = true; Func <IDomainEvent, Task> lambda = async(e) => simpleCalled = true; try { var evt1 = new EventDispatchedOne(); var evt2 = new EventDispatchedTwo(); var collection = new BaseDomainEvent[] { evt1, evt2 }; CoreDispatcher.OnEventDispatched += lambda; CoreDispatcher.OnEventsDispatched += lambdaMulti; await CoreDispatcher.PublishEventsRangeAsync(collection); simpleCalled.Should().BeFalse(); multipleCalled.Should().BeTrue(); } finally { CoreDispatcher.OnEventDispatched -= lambda; CoreDispatcher.OnEventsDispatched -= lambdaMulti; } }
/// <summary> /// Publish all domain events holded by the aggregate with a specified dispatcher. /// </summary> /// <param name="dispatcher">Dispatcher used for publishing.</param> public async Task PublishDomainEventsAsync(IDispatcher dispatcher) { await _lockSecurity.WaitAsync().ConfigureAwait(false); try { if (_domainEvents.Count > 0) { foreach (var evt in _domainEvents) { if (evt.AggregateId == null || evt.AggregateType == null) { if (evt is BaseDomainEvent baseEvt) { if (baseEvt.AggregateId == null) { baseEvt.AggregateId = Id; } if (baseEvt.AggregateType == null) { baseEvt.AggregateType = GetType(); } } else { var props = evt.GetType().GetAllProperties(); if (evt.AggregateId == null) { var aggIdProp = props.FirstOrDefault(p => p.Name == nameof(IDomainEvent.AggregateId)); aggIdProp?.SetMethod?.Invoke(evt, new object[] { Id }); } if (evt.AggregateType == null) { var aggTypeProp = props.FirstOrDefault(p => p.Name == nameof(IDomainEvent.AggregateType)); aggTypeProp?.SetMethod?.Invoke(evt, new object[] { GetType() }); } } } } if (dispatcher == null) { await CoreDispatcher.PublishEventsRangeAsync(_domainEvents).ConfigureAwait(false); } else { await dispatcher.PublishEventsRangeAsync(_domainEvents).ConfigureAwait(false); } _domainEvents.Clear(); } } finally { _lockSecurity.Release(); } }