using System.Reflection; using Elsa.Mediator.Contracts; namespace Elsa.Mediator.Extensions; /// /// Contains helper methods for invoking notification handlers. /// public static class HandlerExtensions { /// /// Gets the handle method for a notification handler of the given notification type. /// /// The notification type. /// The handle method. public static MethodInfo GetNotificationHandlerMethod(this Type notificationType) { var handlerType = typeof(INotificationHandler<>).MakeGenericType(notificationType); return handlerType.GetMethod("HandleAsync")!; } /// /// Gets the handle method for a command handler of the given command type. /// /// The command type. /// The handle method. public static MethodInfo GetCommandHandlerMethod(this Type commandType) { var handlerType = typeof(ICommandHandler<>).MakeGenericType(commandType); return handlerType.GetMethod("HandleAsync")!; } /// /// Invokes the given handler for the given notification. /// /// The handler to invoke. /// The handle method. /// The notification to handle. /// The cancellation token. public static Task InvokeAsync(this INotificationHandler handler, MethodBase handleMethod, INotification notification, CancellationToken cancellationToken) { return (Task)handleMethod.Invoke(handler, new object?[] { notification, cancellationToken })!; } /// /// Invokes the given handler for the given command. /// /// The handler to invoke. /// The handle method. /// The command to handle. /// The cancellation token. public static Task InvokeAsync(this ICommandHandler handler, MethodBase handleMethod, ICommand command, CancellationToken cancellationToken) { var task = (Task)handleMethod.Invoke(handler, new object?[] { command, cancellationToken })!; return task; } }