Clean Architecture Demo
Loading...
Searching...
No Matches
InProcessDomainEventDispatcher.cs
Go to the documentation of this file.
1// TaskManagement.Infrastructure/EventDispatching/InProcessDomainEventDispatcher.cs
2using Microsoft.Extensions.DependencyInjection;
6
8
27{
28 private readonly IServiceProvider _serviceProvider;
29
30 public InProcessDomainEventDispatcher(IServiceProvider serviceProvider)
31 {
32 _serviceProvider = serviceProvider;
33 }
34
35 public async Task DispatchAsync(
36 IReadOnlyCollection<DomainEvent> events,
37 CancellationToken cancellationToken = default)
38 {
39 ArgumentNullException.ThrowIfNull(events);
40
41 foreach (var domainEvent in events)
42 {
43 // El tipo concreto del evento se conoce recién en tiempo de ejecución.
44 var handlerType = typeof(IDomainEventSubscriber<>).MakeGenericType(domainEvent.GetType());
45 var handleMethod = handlerType.GetMethod(nameof(IDomainEventSubscriber<DomainEvent>.HandleAsync))!;
46
47 foreach (var handler in _serviceProvider.GetServices(handlerType))
48 {
49 await ((Task)handleMethod.Invoke(handler, [domainEvent, cancellationToken])!).ConfigureAwait(false);
50 }
51 }
52 }
53}
async Task DispatchAsync(IReadOnlyCollection< DomainEvent > events, CancellationToken cancellationToken=default)
IDomainEventDispatcher es la interfaz para publicación de eventos del dominio.