$mermaidjs
Clean Architecture Demo
Loading...
Searching...
No Matches
MediatRDomainEventDispatcher.cs
Go to the documentation of this file.
1// TaskManagement.Infrastructure/EventDispatching/MediatRDomainEventDispatcher.cs
2using MediatR;
3using Microsoft.Extensions.Logging;
6
8
9#pragma warning disable CS1570 // XML comment has badly formed XML
57#pragma warning restore CS1570 // XML comment has badly formed XML
59{
60 private readonly IMediator _mediator;
61
62 public MediatRDomainEventDispatcher(IMediator mediator)
63 {
64 _mediator = mediator;
65 }
66
67 public async Task DispatchAsync(
68 IReadOnlyCollection<DomainEvent> events,
69 CancellationToken cancellationToken = default)
70 {
71 ArgumentNullException.ThrowIfNull(events);
72
73 foreach (var domainEvent in events)
74 {
75 // Envolver eventos del dominio en INotification para MediatR
76 var notification = WrapEvent(domainEvent);
77 await _mediator.Publish(notification, cancellationToken).ConfigureAwait(false);
78 }
79 }
80
81 private static INotification WrapEvent(DomainEvent domainEvent)
82 {
83 var wrapperType = typeof(DomainEventWrapper<>).MakeGenericType(domainEvent.GetType());
84 return (INotification)Activator.CreateInstance(wrapperType, domainEvent)!;
85 }
86}
87
88public sealed class DomainEventWrapper<T> : INotification where T : DomainEvent
89{
90 public T Event {
91 get;
92 }
93
94 public DomainEventWrapper(T @event) => Event = @event;
95}
96
97// Ejemplo de manejador de eventos
99 : INotificationHandler<DomainEventWrapper<TaskCompletedEvent>>
100{
101 private static readonly Action<ILogger, Guid, DateTime, Exception?> LogTaskCompleted =
102 LoggerMessage.Define<Guid, DateTime>(
103 LogLevel.Information,
104 new EventId(1001, nameof(TaskCompletedNotificationHandler)),
105 "Task {TaskId} completed at {CompletedAt}");
106
107 private readonly IEmailService _emailService;
108 private readonly ILogger<TaskCompletedNotificationHandler> _logger;
109
111 IEmailService emailService,
112 ILogger<TaskCompletedNotificationHandler> logger)
113 {
114 _emailService = emailService;
115 _logger = logger;
116 }
117 public Task Handle(
119 CancellationToken cancellationToken)
120 {
121 ArgumentNullException.ThrowIfNull(notification);
122
123 var @event = notification.Event;
124
125 LogTaskCompleted(_logger, @event.TaskId, @event.CompletedAt, null);
126 return Task.CompletedTask;
127 // Send notification email, update analytics, etc.
128 // await _emailService.SendTaskCompletedNotificationAsync(@event.TaskId);
129 }
130}
builder.Services. typeof(ValidationBehavior<,>)) .AddDbContext< TaskDbContext >(options
DomainEvent es una clase base abstracta para todos los eventos del dominio en el sistema.
MediatRDomainEventDispatcher es la implementación de publicación de eventos del dominio utilizando Me...
async Task DispatchAsync(IReadOnlyCollection< DomainEvent > events, CancellationToken cancellationToken=default)
TaskCompletedNotificationHandler(IEmailService emailService, ILogger< TaskCompletedNotificationHandler > logger)
Task Handle(DomainEventWrapper< TaskCompletedEvent > notification, CancellationToken cancellationToken)
IDomainEventDispatcher es la interfaz para publicación de eventos del dominio.
IEmailService es la abstracción para envío de notificaciones por correo electrónico.