Gericke
Gericke

Reputation: 2241

When executing API method using MediatR, getting an error

It is my 1st time implementing Mediator but now I get the following error when calling API method:

ERROR

{"error":"Enumerator failed to MoveNextAsync."}

DI

services.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>));

Base API

[ApiController]
[Route("api/[controller]")]
public abstract class ApiController : ControllerBase
{
    private IMediator _mediator;

    protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}

API

[HttpGet]
[Route("client/{clientId}/template/list")]
public async Task<ActionResult<TemplateListDTO>> GetClientTemplateList(long clientId)
{
    return await Mediator.Send(new GetClientTemplateListQuery { ClientId = clientId });
}

I am using DotNet core 3.1

Upvotes: 4

Views: 1314

Answers (2)

Gericke
Gericke

Reputation: 2241

I found the problem, it wasn't with Mediator. An exception occurred in the pipeline which was handled incorrectly and couldn't go to the next() pipeline.

Upvotes: 0

Kiksen
Kiksen

Reputation: 1767

The issue is described here:

https://github.com/jbogard/MediatR/issues/317

Ah. You can't do generic type constraints with vanilla MS.Extensions.DI. See my PR to fix this: https://github.com/aspnet/DependencyInjection/pull/635

Do something like the following:

services.AddScoped(typeof(IPipelineBehavior<CustomerAddRequest, CommandResponse>), typeof(CustomerAddBehavior<CustomerAddRequest, CommandResponse>));
services.AddScoped(typeof(IPipelineBehavior<BrandDeleteRequest, CommandResponse>), typeof(BrandDeleteBehavior<BrandDeleteRequest, CommandResponse>));
services.AddScoped(typeof(IPipelineBehavior<CustomerDeleteRequest, CommandResponse>), typeof(CustomerDeleteBehavior<CustomerDeleteRequest, CommandResponse>));

Upvotes: 2

Related Questions