Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to Support Dispatching Events with Non-Integer IDs #5

Merged
merged 1 commit into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Ardalis.SharedKernel/IDomainEventDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
public interface IDomainEventDispatcher
{
Task DispatchAndClearEvents(IEnumerable<EntityBase> entitiesWithEvents);
Task DispatchAndClearEvents<TId>(IEnumerable<EntityBase<TId>> entitiesWithEvents) where TId : struct, IEquatable<TId>;
}
14 changes: 14 additions & 0 deletions src/Ardalis.SharedKernel/MediatRDomainEventDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,19 @@ public async Task DispatchAndClearEvents(IEnumerable<EntityBase> entitiesWithEve
}
}
}

public async Task DispatchAndClearEvents<TId>(IEnumerable<EntityBase<TId>> entitiesWithEvents)
where TId : struct, IEquatable<TId>
{
foreach (var entity in entitiesWithEvents)
{
var events = entity.DomainEvents.ToArray();
entity.ClearDomainEvents();
foreach (var domainEvent in events)
{
await _mediator.Publish(domainEvent).ConfigureAwait(false);
}
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using FluentAssertions;
using MediatR;
using Moq;
using Xunit;

namespace Ardalis.SharedKernel.UnitTests.MediatRDomainEventDispatcherTests;

public class DispatchAndClearEventsWithGuidId
{
private class TestDomainEvent : DomainEventBase { }
private class TestEntity : EntityBase<Guid>
{
public void AddTestDomainEvent()
{
var domainEvent = new TestDomainEvent();
RegisterDomainEvent(domainEvent);
}
}

[Fact]
public async void CallsPublishAndClearDomainEvents()
{
// Arrange
var mediatorMock = new Mock<IMediator>();
var domainEventDispatcher = new MediatRDomainEventDispatcher(mediatorMock.Object);
var entity = new TestEntity();
entity.AddTestDomainEvent();

// Act
await domainEventDispatcher.DispatchAndClearEvents(new List<EntityBase<Guid>> { entity });

// Assert
mediatorMock.Verify(m => m.Publish(It.IsAny<DomainEventBase>(), It.IsAny<CancellationToken>()), Times.Once);
entity.DomainEvents.Should().BeEmpty();
}
}
Loading