net core-领域事件
参考:https://blog.csdn.net/qq_33649351/article/details/120067864
一. 定义领域通知接口
public interface IDomainEvent : INotification { }
二.定义具体领域通知事件
public class OrderCreatedDomainEvent : IDomainEvent { public Order Order { get; private set; } public OrderCreatedDomainEvent(Order order) { this.Order = order; } }
三.在实体父类中增加对领域事件的处理
#region 领域事件的处理 private List<IDomainEvent> _domainEvents; public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents?.AsReadOnly(); public void AddDomainEvent(IDomainEvent eventItem) { _domainEvents = _domainEvents ?? new List<IDomainEvent>(); _domainEvents.Add(eventItem); } public void RemoveDomainEvent(IDomainEvent eventItem) { _domainEvents?.Remove(eventItem); } public void ClearDomainEvents() { _domainEvents?.Clear(); }
#endregion
四,在具体领域实体对象更新时增加相应的领域事件
public class Order : Entity<long>, IAggregateRoot { public string UserId { get; private set; } public string UserName { get; private set; } public Address Address { get; private set; } public int ItemCount { get; private set; } protected Order() { } public Order(string userId, string userName, int itemCount, Address address) { this.UserId = userId; this.UserName = userName; this.Address = address; this.ItemCount = itemCount; //添加OrderCreatedDomainEvent领域事件 this.AddDomainEvent(new OrderCreatedDomainEvent(this)); } } }
五. EFContext 中实现领域事件的发送
#region IUnitOfWork public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default) { var result = await base.SaveChangesAsync(cancellationToken); //实现领域事件的发送 await _mediator.DispatchDomainEventsAsync(this); return true; } #endregion
static class MediatorExtension { public static async Task DispatchDomainEventsAsync(this IMediator mediator, DbContext ctx) { var domainEntities = ctx.ChangeTracker .Entries<Entity>() .Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()); var domainEvents = domainEntities .SelectMany(x => x.Entity.DomainEvents) .ToList(); domainEntities.ToList() .ForEach(entity => entity.Entity.ClearDomainEvents()); foreach (var domainEvent in domainEvents) await mediator.Publish(domainEvent); } }
待续。。