【问题标题】:Handling Exception throwed in a MediatR event ran as a hangfire job处理 MediatR 事件中抛出的异常作为 hangfire 作业运行
【发布时间】:2019-11-15 07:44:47
【问题描述】:

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

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 处理此异常并重试该作业?该作业应该是失败的/计划的。但是 mediatr 事件处理程序中的这个异常似乎在没有告诉挂火的情况下接受了异常......

【问题讨论】:

    标签: c# .net jobs hangfire mediatr


    【解决方案1】:

    我发现Wait()是解决办法:

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

    但我不知道为什么......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多