处理 MediatR 事件 运行 中抛出的异常作为 hangfire 作业

Handling Exception throwed in a MediatR event ran as a hangfire job

我使用 Hangfire 将 mediatR 配置为 运行 事件,就像这样:

public static class MediatRExtension
{
    public static void Enqueue(this IMediator mediator, INotification @event)
    {
        BackgroundJob.Enqueue<HangfireMediator>(m => m.PublishEvent(@event));
    }
}

public class HangfireMediator
{
    private readonly IMediator _mediator;

    public HangfireMediator(IMediator mediator)
    {
        _mediator = mediator;
    }

    public void PublishEvent(INotification @event)
    {
        _mediator.Publish(@event);
    }
}

还有一些要开始的配置:

    public static IGlobalConfiguration UseMediatR(this IGlobalConfiguration config, IMediator mediator)
    {
        config.UseActivator(new MediatRJobActivator(mediator));

        config.UseSerializerSettings(new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Objects
        });

        return config;
    }

public class MediatRJobActivator : JobActivator
{
    private readonly IMediator _mediator;

    public MediatRJobActivator(IMediator mediator)
    {
        _mediator = mediator;
    }

    public override object ActivateJob(Type type)
    {
        return new HangfireMediator(_mediator);
    }
}

现在我称之为 API 的端点它调用:

_mediator.Enqueue(@event);
return Ok();

问题是当我在 EventHandler(来自 mediatr)中抛出异常时。在 hangfire 仪表板中,此作业位于“成功”选项卡中,如下所示

如何让 hangfire 处理这个异常并重试作业?这份工作应该是Failed/Scheduled。但是 mediatr 事件处理程序中的这个异常似乎在没有告诉 hangfire 的情况下接受了异常...

我发现 Wait() 是解决方案:

    public void PublishEvent(INotification @event)
    {
        _mediator.Publish(@event).Wait();
    }

但我不知道为什么...