#region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Events; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Concurrent; using System.Reflection; using System.Threading; using System.Threading.Tasks; #endregion namespace Lumina.Infrastructure.Common.DomainEvents; /// /// Publishes domain events to all handlers registered for the event type, by resolving them from the dependency injection container. /// public class DomainEventPublisher : IDomainEventPublisher { private static readonly ConcurrentDictionary> s_dispatchers = new(); private readonly IServiceProvider _serviceProvider; /// /// Initializes a new instance of the class. /// /// Injected provider used to resolve the domain event handlers. public DomainEventPublisher(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// /// Publishes the specified to all its registered handlers, in registration order. /// /// The domain event to publish. /// Token to monitor for cancellation requests. /// A task that represents the asynchronous operation. public ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(domainEvent); Func dispatcher = s_dispatchers.GetOrAdd(domainEvent.GetType(), static eventType => { MethodInfo dispatchMethod = typeof(DomainEventPublisher).GetMethod(nameof(DispatchAsync), BindingFlags.NonPublic | BindingFlags.Static)! .MakeGenericMethod(eventType); return dispatchMethod.CreateDelegate>(); }); return new ValueTask(dispatcher(domainEvent, _serviceProvider, cancellationToken)); } /// /// Dispatches the specified to all handlers registered for . /// /// The type of the domain event being dispatched. /// The domain event to dispatch. /// The provider used to resolve the domain event handlers. /// Token to monitor for cancellation requests. /// A task that represents the asynchronous operation. private static async Task DispatchAsync(IDomainEvent domainEvent, IServiceProvider serviceProvider, CancellationToken cancellationToken) where TDomainEvent : IDomainEvent { foreach (IDomainEventHandler handler in serviceProvider.GetServices>()) await handler.HandleAsync((TDomainEvent)domainEvent, cancellationToken).ConfigureAwait(false); } }