using CAPI.Custom.Services.EventHandlers; using CAPI.Custom.Services.Events; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace CAPI.Custom.Services { public static class DomainEvents { private static List _handlers; public static void Init() { _handlers = Assembly.GetExecutingAssembly() .GetTypes() .Where(x => x.GetInterfaces().Any(y => y.IsGenericType && y.GetGenericTypeDefinition() == typeof(IHandler<>))) .ToList(); } public static void Dispatch(IEvent domainEvent) { foreach (Type handlerType in _handlers) { bool canHandleEvent = handlerType.GetInterfaces() .Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IHandler<>) && x.GenericTypeArguments[0] == domainEvent.GetType()); if (canHandleEvent) { dynamic handler = Activator.CreateInstance(handlerType); handler.Handle((dynamic)domainEvent); } } } } }