I configured mediatR to run events using Hangfire simply like that:
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);
}
}
And some more configuration to get started:
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);
}
}
And now what I call my API endpoint it calls:
_mediator.Enqueue(@event);
return Ok();
The problem is when in the EventHandler (from mediatr) I throw an Exception. In hangfire dashboard this job is in the Succeeded tab as you can see below
How can I tell hangfire to handle this exception and retry the job again? This job should be Failed/Scheduled. But this exception in mediatr event handler seems like takes the exception without telling the hangfire about it...
I found that Wait()
is the solution:
public void PublishEvent(INotification @event)
{
_mediator.Publish(@event).Wait();
}
But I have no clue why...