Skip to content

Commit b9c1778

Browse files
Refactoring Domain Events so it is clear and differenciated versus Integration Events
1 parent 6f6f09e commit b9c1778

12 files changed

Lines changed: 50 additions & 45 deletions

File tree

src/Services/Ordering/Ordering.API/Application/EventHandlers/OrderCreatedEventHandler.cs renamed to src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/OrderCreatedDomainEventHandler.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,22 @@
66
using System;
77
using System.Threading.Tasks;
88

9-
namespace Ordering.API.Application.EventHandlers
9+
namespace Ordering.API.Application.DomainEventHandlers
1010
{
11-
public class OrderCreatedEventHandler : IAsyncNotificationHandler<OrderCreated>
11+
public class OrderCreatedDomainEventHandler : IAsyncNotificationHandler<OrderCreatedDomainEvent>
1212
{
1313
private readonly ILoggerFactory _logger;
1414
private readonly IBuyerRepository<Buyer> _buyerRepository;
1515
private readonly IIdentityService _identityService;
1616

17-
public OrderCreatedEventHandler(ILoggerFactory logger, IBuyerRepository<Buyer> buyerRepository, IIdentityService identityService)
17+
public OrderCreatedDomainEventHandler(ILoggerFactory logger, IBuyerRepository<Buyer> buyerRepository, IIdentityService identityService)
1818
{
1919
_buyerRepository = buyerRepository ?? throw new ArgumentNullException(nameof(buyerRepository));
2020
_identityService = identityService ?? throw new ArgumentNullException(nameof(identityService));
2121
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
2222
}
2323

24-
public async Task Handle(OrderCreated orderNotification)
24+
public async Task Handle(OrderCreatedDomainEvent orderNotification)
2525
{
2626
var cardTypeId = orderNotification.CardTypeId != 0 ? orderNotification.CardTypeId : 1;
2727

@@ -46,7 +46,7 @@ public async Task Handle(OrderCreated orderNotification)
4646
await _buyerRepository.UnitOfWork
4747
.SaveEntitiesAsync();
4848

49-
_logger.CreateLogger(nameof(OrderCreatedEventHandler)).LogTrace($"A new payment method has been successfully added for orderId: {orderNotification.Order.Id}.");
49+
_logger.CreateLogger(nameof(OrderCreatedDomainEventHandler)).LogTrace($"A new payment method has been successfully added for orderId: {orderNotification.Order.Id}.");
5050

5151
}
5252
}

src/Services/Ordering/Ordering.API/Application/EventHandlers/PaymentMethodCheckedEventHandler.cs renamed to src/Services/Ordering/Ordering.API/Application/DomainEventHandlers/PaymentMethodCheckedDomainEventHandler.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,19 @@
55
using System;
66
using System.Threading.Tasks;
77

8-
namespace Ordering.API.Application.EventHandlers
8+
namespace Ordering.API.Application.DomainEventHandlers
99
{
10-
public class PaymentMethodCheckedEventHandler : IAsyncNotificationHandler<PaymentMethodChecked>
10+
public class PaymentMethodCheckedDomainEventHandler : IAsyncNotificationHandler<PaymentMethodCheckedDomainEvent>
1111
{
1212
private readonly IOrderRepository<Order> _orderRepository;
1313
private readonly ILoggerFactory _logger;
14-
public PaymentMethodCheckedEventHandler(IOrderRepository<Order> orderRepository, ILoggerFactory logger)
14+
public PaymentMethodCheckedDomainEventHandler(IOrderRepository<Order> orderRepository, ILoggerFactory logger)
1515
{
1616
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
1717
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
1818
}
1919

20-
public async Task Handle(PaymentMethodChecked paymentMethodNotification)
20+
public async Task Handle(PaymentMethodCheckedDomainEvent paymentMethodNotification)
2121
{
2222
var orderToUpdate = await _orderRepository.GetAsync(paymentMethodNotification.OrderId);
2323
orderToUpdate.SetBuyerId(paymentMethodNotification.Buyer.Id);
@@ -26,7 +26,7 @@ public async Task Handle(PaymentMethodChecked paymentMethodNotification)
2626
await _orderRepository.UnitOfWork
2727
.SaveEntitiesAsync();
2828

29-
_logger.CreateLogger(nameof(PaymentMethodCheckedEventHandler))
29+
_logger.CreateLogger(nameof(PaymentMethodCheckedDomainEventHandler))
3030
.LogTrace($"Order with Id: {paymentMethodNotification.OrderId} has been successfully updated with a new payment method id: { paymentMethodNotification.Payment.Id }");
3131
}
3232
}

src/Services/Ordering/Ordering.API/Infrastructure/AutofacModules/MediatorModule.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
using MediatR;
44
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands;
55
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Decorators;
6-
using Ordering.API.Application.EventHandlers;
6+
using Ordering.API.Application.DomainEventHandlers;
77
using Ordering.Domain.Events;
88
using System.Collections.Generic;
99
using System.Linq;
@@ -24,7 +24,7 @@ protected override void Load(ContainerBuilder builder)
2424
.Select(i => new KeyedService("IAsyncRequestHandler", i)));
2525

2626
builder
27-
.RegisterAssemblyTypes(typeof(OrderCreatedEventHandler).GetTypeInfo().Assembly)
27+
.RegisterAssemblyTypes(typeof(OrderCreatedDomainEventHandler).GetTypeInfo().Assembly)
2828
.Where(t => t.IsClosedTypeOf(typeof(IAsyncNotificationHandler<>)))
2929
.AsImplementedInterfaces();
3030

src/Services/Ordering/Ordering.Domain/AggregatesModel/BuyerAggregate/Buyer.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,15 @@ public PaymentMethod AddPaymentMethod(
3333

3434
if (existingPayment != null)
3535
{
36-
AddEvent(new PaymentMethodChecked(this, existingPayment, orderId));
36+
AddDomainEvent(new PaymentMethodCheckedDomainEvent(this, existingPayment, orderId));
3737
return existingPayment;
3838
}
3939
else
4040
{
4141
var payment = new PaymentMethod(cardTypeId, alias, cardNumber, securityNumber, cardHolderName, expiration);
4242

4343
_paymentMethods.Add(payment);
44-
AddEvent(new PaymentMethodChecked(this, payment, orderId));
44+
AddDomainEvent(new PaymentMethodCheckedDomainEvent(this, payment, orderId));
4545
return payment;
4646
}
4747
}

src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,10 @@ public Order(Address address, int cardTypeId, string cardNumber, string cardSecu
5151
_orderStatusId = OrderStatus.InProcess.Id;
5252
_orderDate = DateTime.UtcNow;
5353
Address = address;
54-
AddCreatedOrderEvent(cardTypeId, cardNumber,
54+
55+
// Add the OrderCreatedEvent to the domain events collection
56+
// to be raised/dispatched when comitting changes into the Database [ After DbContext.SaveChanges() ]
57+
AddOrderCreatedDomainEvent(cardTypeId, cardNumber,
5558
cardSecurityNumber, cardHolderName, cardExpiration);
5659
}
5760

@@ -93,14 +96,14 @@ public void SetBuyerId(int id)
9396
_buyerId = id;
9497
}
9598

96-
private void AddCreatedOrderEvent(int cardTypeId, string cardNumber,
99+
private void AddOrderCreatedDomainEvent(int cardTypeId, string cardNumber,
97100
string cardSecurityNumber, string cardHolderName, DateTime cardExpiration)
98101
{
99-
var @orderCreatedEvent = new OrderCreated(
102+
var orderCreatedDomainEvent = new OrderCreatedDomainEvent(
100103
this, cardTypeId, cardNumber, cardSecurityNumber,
101104
cardHolderName, cardExpiration);
102105

103-
AddEvent(@orderCreatedEvent);
106+
AddDomainEvent(orderCreatedDomainEvent);
104107
}
105108
}
106109
}

src/Services/Ordering/Ordering.Domain/Events/OrderCreated.cs renamed to src/Services/Ordering/Ordering.Domain/Events/OrderCreatedDomainEvent.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Ordering.Domain.Events
99
/// <summary>
1010
/// Event used when an order is created
1111
/// </summary>
12-
public class OrderCreated
12+
public class OrderCreatedDomainEvent
1313
: IAsyncNotification
1414
{
1515
public int CardTypeId { get; private set; }
@@ -19,7 +19,7 @@ public class OrderCreated
1919
public DateTime CardExpiration { get; private set; }
2020
public Order Order { get; private set; }
2121

22-
public OrderCreated(Order order,
22+
public OrderCreatedDomainEvent(Order order,
2323
int cardTypeId, string cardNumber,
2424
string cardSecurityNumber, string cardHolderName,
2525
DateTime cardExpiration)

src/Services/Ordering/Ordering.Domain/Events/PaymentMethodChecked.cs renamed to src/Services/Ordering/Ordering.Domain/Events/PaymentMethodCheckedDomainEvent.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66

77
namespace Ordering.Domain.Events
88
{
9-
public class PaymentMethodChecked
9+
public class PaymentMethodCheckedDomainEvent
1010
: IAsyncNotification
1111
{
1212
public Buyer Buyer { get; private set; }
1313
public PaymentMethod Payment { get; private set; }
1414
public int OrderId { get; private set; }
1515

16-
public PaymentMethodChecked(Buyer buyer, PaymentMethod payment, int orderId)
16+
public PaymentMethodCheckedDomainEvent(Buyer buyer, PaymentMethod payment, int orderId)
1717
{
1818
Buyer = buyer;
1919
Payment = payment;

src/Services/Ordering/Ordering.Domain/SeedWork/Entity.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public abstract class Entity
1010
int? _requestedHashCode;
1111
int _Id;
1212

13-
private List<IAsyncNotification> _events;
13+
private List<IAsyncNotification> _domainEvents;
1414

1515
public virtual int Id
1616
{
@@ -24,17 +24,17 @@ protected set
2424
}
2525
}
2626

27-
public List<IAsyncNotification> Events => _events;
28-
public void AddEvent(IAsyncNotification eventItem)
27+
public List<IAsyncNotification> DomainEvents => _domainEvents;
28+
public void AddDomainEvent(IAsyncNotification eventItem)
2929
{
30-
_events = _events ?? new List<IAsyncNotification>();
31-
_events.Add(eventItem);
30+
_domainEvents = _domainEvents ?? new List<IAsyncNotification>();
31+
_domainEvents.Add(eventItem);
3232
}
3333

34-
public void RemoveEvent(IAsyncNotification eventItem)
34+
public void RemoveDomainEvent(IAsyncNotification eventItem)
3535
{
36-
if (_events is null) return;
37-
_events.Remove(eventItem);
36+
if (_domainEvents is null) return;
37+
_domainEvents.Remove(eventItem);
3838
}
3939

4040
public bool IsTransient()

src/Services/Ordering/Ordering.Infrastructure/MediatorExtension.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ public static class MediatorExtension
1010
{
1111
public static async Task RaiseDomainEventsAsync(this IMediator mediator, OrderingContext ctx)
1212
{
13-
var domainEntities = ctx.ChangeTracker.Entries<Entity>().Where(x => x.Entity.Events != null && x.Entity.Events.Any());
14-
var domainEvents = domainEntities.SelectMany(x => x.Entity.Events).ToList();
15-
domainEntities.ToList().ForEach(entity => entity.Entity.Events.Clear());
13+
var domainEntities = ctx.ChangeTracker.Entries<Entity>().Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any());
14+
var domainEvents = domainEntities.SelectMany(x => x.Entity.DomainEvents).ToList();
15+
domainEntities.ToList().ForEach(entity => entity.Entity.DomainEvents.Clear());
1616

1717
var tasks = domainEvents
1818
.Select(async (domainEvent) => {

src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ void ConfigureBuyer(EntityTypeBuilder<Buyer> buyerConfiguration)
7474

7575
buyerConfiguration.HasKey(b => b.Id);
7676

77-
buyerConfiguration.Ignore(b => b.Events);
77+
buyerConfiguration.Ignore(b => b.DomainEvents);
7878

7979
buyerConfiguration.Property(b => b.Id)
8080
.ForSqlServerUseSequenceHiLo("buyerseq", DEFAULT_SCHEMA);
@@ -102,7 +102,7 @@ void ConfigurePayment(EntityTypeBuilder<PaymentMethod> paymentConfiguration)
102102

103103
paymentConfiguration.HasKey(b => b.Id);
104104

105-
paymentConfiguration.Ignore(b => b.Events);
105+
paymentConfiguration.Ignore(b => b.DomainEvents);
106106

107107
paymentConfiguration.Property(b => b.Id)
108108
.ForSqlServerUseSequenceHiLo("paymentseq", DEFAULT_SCHEMA);
@@ -139,7 +139,7 @@ void ConfigureOrder(EntityTypeBuilder<Order> orderConfiguration)
139139

140140
orderConfiguration.HasKey(o => o.Id);
141141

142-
orderConfiguration.Ignore(b => b.Events);
142+
orderConfiguration.Ignore(b => b.DomainEvents);
143143

144144
orderConfiguration.Property(o => o.Id)
145145
.ForSqlServerUseSequenceHiLo("orderseq", DEFAULT_SCHEMA);
@@ -176,7 +176,7 @@ void ConfigureOrderItems(EntityTypeBuilder<OrderItem> orderItemConfiguration)
176176

177177
orderItemConfiguration.HasKey(o => o.Id);
178178

179-
orderItemConfiguration.Ignore(b => b.Events);
179+
orderItemConfiguration.Ignore(b => b.DomainEvents);
180180

181181
orderItemConfiguration.Property(o => o.Id)
182182
.ForSqlServerUseSequenceHiLo("orderitemseq");
@@ -238,6 +238,8 @@ void ConfigureCardTypes(EntityTypeBuilder<CardType> cardTypesConfiguration)
238238
public async Task<int> SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken))
239239
{
240240
var result = await base.SaveChangesAsync();
241+
242+
// Dispatch the Domain Events collection right after saving/commiting data into the database
241243
await _mediator.RaiseDomainEventsAsync(this);
242244
return result;
243245
}

0 commit comments

Comments
 (0)