| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | using Elsa.Mediator.Contexts; |
| | | 3 | | using Elsa.Mediator.Contracts; |
| | | 4 | | using Elsa.Mediator.Middleware.Command.Contracts; |
| | | 5 | | using JetBrains.Annotations; |
| | | 6 | | using Microsoft.Extensions.DependencyInjection; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Mediator.Middleware.Command.Components; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// A command middleware that invokes the command. |
| | | 12 | | /// </summary> |
| | | 13 | | [UsedImplicitly] |
| | 1 | 14 | | public class CommandHandlerInvokerMiddleware(CommandMiddlewareDelegate next) : ICommandMiddleware |
| | | 15 | | { |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | [UnconditionalSuppressMessage("Trimming", "IL2060:Call to MakeGenericMethod can not be statically analyzed", Justifi |
| | | 18 | | public async ValueTask InvokeAsync(CommandContext context) |
| | | 19 | | { |
| | | 20 | | // Find all handlers for the specified command. |
| | 55 | 21 | | var command = context.Command; |
| | 55 | 22 | | var commandType = command.GetType(); |
| | 55 | 23 | | var resultType = context.ResultType; |
| | 55 | 24 | | var handlerType = typeof(ICommandHandler<,>).MakeGenericType(commandType, resultType); |
| | 55 | 25 | | var serviceProvider = context.ServiceProvider; |
| | 55 | 26 | | var commandHandlers = serviceProvider.GetServices<ICommandHandler>(); |
| | 495 | 27 | | var handlers = commandHandlers.DistinctBy(x => x.GetType()).Where(x => handlerType.IsInstanceOfType(x)).ToArray( |
| | | 28 | | |
| | 55 | 29 | | if (handlers.Length == 0) |
| | 0 | 30 | | throw new InvalidOperationException($"There is no handler to handle the {commandType.FullName} command"); |
| | | 31 | | |
| | 55 | 32 | | if (handlers.Length > 1) |
| | 0 | 33 | | throw new InvalidOperationException($"Multiple handlers were found to handle the {commandType.FullName} comm |
| | | 34 | | |
| | 55 | 35 | | var handler = handlers.First(); |
| | 55 | 36 | | var strategyContext = new CommandStrategyContext(context, handler, serviceProvider, context.CancellationToken); |
| | 55 | 37 | | var strategy = context.CommandStrategy; |
| | 55 | 38 | | var executeMethod = strategy.GetType().GetMethod(nameof(ICommandStrategy.ExecuteAsync))!; |
| | 55 | 39 | | var executeMethodWithReturnType = executeMethod.MakeGenericMethod(resultType); |
| | | 40 | | |
| | | 41 | | // Execute command. |
| | 55 | 42 | | var task = executeMethodWithReturnType.Invoke(strategy, [strategyContext]); |
| | | 43 | | |
| | | 44 | | // Get the result of the task. |
| | 55 | 45 | | var taskWithReturnType = typeof(Task<>).MakeGenericType(resultType); |
| | 55 | 46 | | var resultProperty = taskWithReturnType.GetProperty(nameof(Task<object>.Result))!; |
| | 55 | 47 | | context.Result = resultProperty.GetValue(task); |
| | | 48 | | |
| | | 49 | | // Invoke next middleware. |
| | 55 | 50 | | await next(context); |
| | 55 | 51 | | } |
| | | 52 | | } |