| | | 1 | | using Elsa.Mediator.Middleware.Command.Contracts; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Mediator.Middleware.Command; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Provides extension methods for <see cref="ICommandPipelineBuilder"/>. |
| | | 8 | | /// </summary> |
| | | 9 | | public static class MiddlewareExtensions |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Adds middleware to the pipeline. |
| | | 13 | | /// </summary> |
| | | 14 | | public static ICommandPipelineBuilder UseMiddleware<TMiddleware>(this ICommandPipelineBuilder builder, params object |
| | | 15 | | { |
| | 4 | 16 | | return builder.Use(next => BuildMiddlewareDelegate<TMiddleware>(builder, next, args)); |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Inserts middleware at a specific index in the pipeline. |
| | | 21 | | /// </summary> |
| | | 22 | | public static ICommandPipelineBuilder UseMiddleware<TMiddleware>(this ICommandPipelineBuilder builder, int index, pa |
| | | 23 | | { |
| | 0 | 24 | | return builder.Use(index, next => BuildMiddlewareDelegate<TMiddleware>(builder, next, args)); |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Builds a delegate for the middleware type. |
| | | 29 | | /// </summary> |
| | | 30 | | private static CommandMiddlewareDelegate BuildMiddlewareDelegate<TMiddleware>( |
| | | 31 | | ICommandPipelineBuilder builder, |
| | | 32 | | CommandMiddlewareDelegate next, |
| | | 33 | | object[] args |
| | | 34 | | ) where TMiddleware : ICommandMiddleware |
| | | 35 | | { |
| | 2 | 36 | | var middleware = typeof(TMiddleware); |
| | 2 | 37 | | var invokeMethod = MiddlewareHelpers.GetInvokeMethod(middleware); |
| | 2 | 38 | | var ctorParams = new[] |
| | 2 | 39 | | { |
| | 2 | 40 | | next |
| | 4 | 41 | | }.Concat(args).Select(x => x!).ToArray(); |
| | 2 | 42 | | var instance = ActivatorUtilities.CreateInstance(builder.ApplicationServices, middleware, ctorParams); |
| | 2 | 43 | | return (CommandMiddlewareDelegate)invokeMethod.CreateDelegate(typeof(CommandMiddlewareDelegate), instance); |
| | | 44 | | } |
| | | 45 | | } |