< Summary

Information
Class: Elsa.Mediator.Middleware.Request.Components.RequestHandlerInvokerMiddleware
Assembly: Elsa.Mediator
File(s): /home/runner/work/elsa-core/elsa-core/src/common/Elsa.Mediator/Middleware/Request/Components/RequestHandlerInvokerMiddleware.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 22
Coverable lines: 22
Total lines: 44
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 4
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
InvokeAsync()0%2040%

File(s)

/home/runner/work/elsa-core/elsa-core/src/common/Elsa.Mediator/Middleware/Request/Components/RequestHandlerInvokerMiddleware.cs

#LineLine coverage
 1using Elsa.Mediator.Contracts;
 2using Elsa.Mediator.Middleware.Request.Contracts;
 3
 4namespace Elsa.Mediator.Middleware.Request.Components;
 5
 6/// <summary>
 7/// A middleware component that invokes request handlers.
 8/// </summary>
 09public class RequestHandlerInvokerMiddleware(
 010    RequestMiddlewareDelegate next,
 011    IEnumerable<IRequestHandler> requestHandlers) : IRequestMiddleware
 12{
 13    /// <inheritdoc />
 14    public async ValueTask InvokeAsync(RequestContext context)
 15    {
 16
 17        // Find all handlers for the specified request.
 018        var request = context.Request;
 019        var requestType = request.GetType();
 020        var responseType = context.ResponseType;
 021        var handlerType = typeof(IRequestHandler<,>).MakeGenericType(requestType, responseType);
 022        var handlers = requestHandlers.Where(x => handlerType.IsInstanceOfType(x)).ToArray();
 23
 024        if (handlers.Length == 0)
 025            throw new InvalidOperationException($"There is no handler to handle the {requestType.FullName} request");
 26
 027        if (handlers.Length > 1)
 028            throw new InvalidOperationException($"Multiple handlers were found to handle the {requestType.FullName} requ
 29
 030        var handler = handlers.First();
 031        var handleMethod = handlerType.GetMethod("HandleAsync")!;
 032        var cancellationToken = context.CancellationToken;
 033        var task = (Task)handleMethod.Invoke(handler, [request, cancellationToken])!;
 034        await task;
 35
 36        // Get result of task.
 037        var taskWithReturnType = typeof(Task<>).MakeGenericType(responseType);
 038        var resultProperty = taskWithReturnType.GetProperty(nameof(Task<object>.Result))!;
 039        context.Response = resultProperty.GetValue(task)!;
 40
 41        // Invoke next middleware.
 042        await next(context);
 043    }
 44}