Followed official doc:
While invoking the handler I get
info: Microsoft.Hosting.Lifetime[0] Content root path: C:\S\Abhi.MediatR.SampleUsingControllers Stack overflow. Repeat 260 times:
Could you help me with, what did is missing?
To invoke the handler, I had created a controller as below:
[Route("api/[controller]")]
[ApiController]
public class PingController : ControllerBase
{
private readonly IMediator mediator;
public PingController(IMediator mediator)
{
this.mediator = mediator;
}
[HttpGet]
[Produces(typeof(string))]
public IActionResult Get()
{
try
{
var response = mediator.Send(new Ping());
return Ok(response);
}
catch (Exception ex)
{
return BadRequest($"Oops something went wrong, {ex}");
}
}
}
Created Ping Request
public class Ping : IRequest<string>
{
}
Created PingHandler:
public class PingHandler : IRequestHandler<Ping, string>
{
private readonly IMediator mediator;
public PingHandler(IMediator mediator)
{
this.mediator = mediator;
}
public async Task<string> Handle(Ping request, CancellationToken cancellationToken)
{
//return Task.FromResult("Pong");
var response = await mediator.Send(new Ping());
return response;
}
}
In Program.cs have added the MediatR
builder.Services.AddMediatR(typeof(Program));
As per doc I also tried adding as below:
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
CodePudding user response:
The exception shows that you have an infinite recursion in your code. Handle
method is again calling the Ping
request again.
you need to uncomment the line return Task.FromResult("Pong");
and comment the below code.
var response = await mediator.Send(new Ping());
return response;