| | | 1 | | using System.Reflection; |
| | | 2 | | |
| | | 3 | | namespace Elsa.Mediator.Middleware; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Provides a set of static methods for working with middleware. |
| | | 7 | | /// </summary> |
| | | 8 | | public static class MiddlewareHelpers |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Gets the Invoke or InvokeAsync method from the middleware type. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="middleware">The middleware type.</param> |
| | | 14 | | /// <returns>The Invoke or InvokeAsync method.</returns> |
| | | 15 | | /// <exception cref="InvalidOperationException">Thrown when the Invoke or InvokeAsync method cannot be found or the |
| | | 16 | | public static MethodInfo GetInvokeMethod(Type middleware) |
| | | 17 | | { |
| | | 18 | | const string invokeMethodName = "Invoke"; |
| | | 19 | | const string invokeAsyncMethodName = "InvokeAsync"; |
| | 3 | 20 | | var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public); |
| | 18 | 21 | | var invokeMethods = methods.Where(m => string.Equals(m.Name, invokeMethodName, StringComparison.Ordinal) || stri |
| | | 22 | | |
| | 3 | 23 | | switch (invokeMethods.Length) |
| | | 24 | | { |
| | | 25 | | case > 1: |
| | 0 | 26 | | throw new InvalidOperationException("Multiple Invoke methods were found. Use either Invoke or InvokeAsyn |
| | | 27 | | case 0: |
| | 0 | 28 | | throw new InvalidOperationException("No Invoke methods were found. Use either Invoke or InvokeAsync"); |
| | | 29 | | } |
| | | 30 | | |
| | 3 | 31 | | var methodInfo = invokeMethods[0]; |
| | | 32 | | |
| | 3 | 33 | | if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType) && !typeof(ValueTask).IsAssignableFrom(methodInfo.Retu |
| | 0 | 34 | | throw new InvalidOperationException($"The {methodInfo.Name} method must return Task or ValueTask"); |
| | | 35 | | |
| | 3 | 36 | | return methodInfo; |
| | | 37 | | } |
| | | 38 | | } |