Stackoverflow异常在MediatR Ping样本?



遵循官方文档:

调用处理程序时,我得到

信息:Microsoft.Hosting.Lifetime [0]内容根路径:C:SAbhi.MediatR。SampleUsingControllersStack overflow重复260次:

你能帮我一下吗,我少了什么?

为了调用处理程序,我创建了一个控制器,如下所示:
[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}");
}
}
}

创建Ping请求

public class Ping : IRequest<string>
{
}

创建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;
}
}

在Program.cs中添加了MediatR

builder.Services.AddMediatR (typeof(程序));

根据文档,我还尝试添加如下内容:

builder.Services.AddMediatR (Assembly.GetExecutingAssembly ());

该异常表明您的代码中存在无限递归。Handle方法再次调用Ping请求

你需要取消return Task.FromResult("Pong");

行注释并注释下面的代码。

var response = await mediator.Send(new Ping());
return response;

相关内容

  • 没有找到相关文章

最新更新