集成事件转换器¶
集成事件转换器将领域事件发送成集成事件的转换工具。
通过集成事件转换器可以将要发送集成事件与其他领域事件处理器中业务逻辑解耦。
定义集成事件转换器¶
- 安装nuget包
NetCorePal.Extensions.DistributedTransactions.Abstractions
dotnet add package NetCorePal.Extensions.DistributedTransactions.Abstractions
-
定义集成事件转换器,需要:
-
继承
NetCorePal.Extensions.DistributedTransactions.IIntegrationEventConverter
接口; - 实现IIntegrationEventConverter接口的Convert方法,该方法入参为领域事件IDomainEvent,返参为集成事件IntegrationEvent
下面为一个示例:
// 定义集成事件转换器
using NetCorePal.Web.Application.IntegrationConvert;
namespace YourNamespace;
public class OrderCreatedIntegrationEventConverter : IIntegrationEventConverter<OrderCreatedDomainEvent,OrderPaidIntegrationEvent>{
public OrderPaidIntegrationEvent Convert(OrderCreatedDomainEvent domainEvent)
{
return new OrderPaidIntegrationEvent(domainEvent.Order.Id);
}
}
- 框架自带代码生成器自动生成集成事件处理器
如下为代码生成器生成的集成事件处理器:
// <auto-generated/>
using NetCorePal.Web.Application.IntegrationConverters;
using NetCorePal.Extensions.DistributedTransactions;
using NetCorePal.Extensions.Domain;
using NetCorePal.Web;
namespace YourNamespace;
{
/// <summary>
/// OrderCreatedIntegrationEventConverterDomainEventHandlers
/// </summary>
public class OrderCreatedIntegrationEventConverterDomainEventHandler(IIntegrationEventPublisher integrationEventPublisher,
OrderCreatedIntegrationEventConverter converter) : IDomainEventHandler<OrderCreatedDomainEvent>
{
/// <summary>
/// OrderCreatedIntegrationEventConverterDomainEventHandler
/// </summary>
/// <param name="notification">notification</param>
/// <param name="cancellationToken">cancellationToken</param>
public async Task Handle(OrderCreatedDomainEvent notification, CancellationToken cancellationToken){
// 转移操作发出集成事件
var integrationEvent = converter.Convert(notification);
await integrationEventPublisher.PublishAsync(integrationEvent, cancellationToken);
}
}
}