Sponsor: Using RabbitMQ or Azure Service Bus in your .NET systems? Well, you could just use their SDKs and roll your own serialization, routing, outbox, retries, and telemetry. I mean, seriously, how hard could it be?

IRequest<Unit>
Because we are creating a a fire and forget command which will be run in the background, there will be no return value. MediatR handles these types of requests by using the Unit type. When creating a command you will implement IRequest and your request handler will implement IRequestHandler<IRequest, Unit>. To send MyCommand you would use MediatR’s Send<T>() where T is the response of the request, in our case Unit.Feedback
In my original post, Darren Cauthon made some suggestions that got me thinking about how I could create a better solution to integrate MediatR and Hangfire a bit better.Extensions
My first task was to create an extension method on MediatR that would Enqueue a command to Hangfire. I took a similar approach to my previous solution by wrapping MediatR’s Send<T>() in a method with no type parameters. In order for the HangfireMediator class to be instantiated, Hangfire providesJobActivator
class to instantiate the target types before invoking instance methods.
Finally, we need to configure Hangfire to use the new Activator as well as configure Json.NET to include type information when serializing. Here we an create an extension method on Hangfires IGlobalConfiguration in order to use our new activator.
Usage
With all our extension methods in place, we can now call our Hangfire extension to pass in our Mediator instance. Now in Enqueue a new command, we can do so from our new MediatR extension.Demo
