I’ve been using MediatR and Hangfire independently for awhile. I’ve previously posted one solution on how you could use send Commands with MediatR and Hangfire.
The solution I had come up with in that post was to get around the expression serialization issue with type parameters in MediatR’s Send<T>.
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.
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.
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 provides
JobActivator 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.
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.
You can find all the source on GitHub
Let me know if you are using MediatR along with Hangfire. Please share in the comments below or on twitter.