Using Hangfire and MediatR as a Message Dispatcher

Two popular libraries in Hangfire and MediatR can be used together to create a pretty powerful out-of-process messaging dispatcher. I’ve covered this a bit many years ago but I figured I’d give it a refresh since it’s a bit easier in the world of ASP.NET Core.


Check out my YouTube channel where I post all kinds of content that accompanies my posts including this video showing everything that is in this post.

Hangfire and MediatR Bridge/Wrapper

The first thing you need to do is create a bridge/wrapper around MediatR. At first this may seem completely pointless, but it has a purpose. Hangfire has a lot extensibility in terms of how jobs are executed that are often times defined by using attributes. Because we don’t own the MediatR library, we need to have our own class that we can defined these attributes on.

Here’s a simple start to our Bridge/Wrapper

In the example above, I have an overload for Send() that accepts the jobName as the first parameter. The DisplayName attribute will be used by Hangfire to show in the UI Dashboard the name of the job. This is a simple example of why we need this wrapper.

MediatR Extensions

The next piece of the puzzle is creating extension methods to be able to use Hangfire to create background jobs. In the example below I’ve created Enqueue() extension methods that use the Hangfire BackgroundJobClient to enqueue work using our Bridge/Wrapper

Hangfire Serialization

In the BackgroundJobClient.Enqueue() above, Hangfire will use Json.NET to serialize the IRequest that we are passing to Send() that ultimately gets put into storage. When Hangfire then pulls that job out of storage to perform the work, it needs to deserialize it. Because it’s just an IRequest it has no way to turning that into a concrete type.

To handle this, we need to configure Hangfire to add type handling when it serializes/deserializes.


The last thing we need to do is actually configure Hangfire in the ConfigureServices of either your ASP.NET Core Startup or your HostBuilder.

Here’s an example of my Worker process. This is just a console app that is purely a Hangfire server that just processes jobs from Hangfire.

Enqueuing a Request

In order to enqueue a MediatR request to Hangfire is a matter of calling the Enqueue() extension method we created off of IMediator.

In the example above, the HTTP Request to our Controller action will return a 204 NoContent, even though we are throwing in our PlaceOrderHandler because it’s execution is actually done out of the context of the HTTP Request. This could either be in a different thread, an entire different process, or on a totally on a different server).


There’s a lot more you can do with this and take it much farther to handle things like event publishing to have each event handler be it’s own job within Hangfire.

You can get all the source code of this running example on my GitHub.

If you have any thoughts or questions, please leave a comment on my blog, Twitter, or on the YouTube video.

Follow @CodeOpinion on Twitter

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.


Moving work Out-of-Process using Brighter and RabbitMQ

Once you start doing in-process request & event dispatching, you’ll soon want to move out-of-process so you can isolate work from the caller/invoker. This is often times the next logical step if you’re using MediatR for commands and especially for events/notifications. Here’s how you can do use the same paradigm for in-process and out-of-process using Brighter and RabbitMQ.


Check out my YouTube channel where I post all kinds of content that accompanies my posts including this video showing you how to move work out-of-process.


For those unfamiliar with MediatR library or the mediator pattern:

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program’s running behavior.

I covered MediatR and why you might want to consider it but also one big drawback in my why use MediatR post.

One of the biggest downside to in-process processing (which MediatR does), is it does isolate the actual handling of a request. This isn’t a problem with MediatR at all, just the nature of it executing in-process.

For example, in the case of ASP.NET Core, you’re tied to the originating HTTP request. If the request your processing throws an exception, that will get bubbled up to ASP.NET Core which will return an HTTP 500 to the client.


Brighter is a command dispatcher and command processor. I’m using it for these examples because if you’re familiar with MediatR, Brighter will seem very similar in terms of the API. It can dispatch requests in-process as well as go out-of-process by using a Message Broker like RabbitMQ.

There’s a whole bunch Brighter can do, but for the purpose of this post, I just want to show you how you can move from In-Process to Out-of-Process rather seamlessly.

In my opinion, using the same paradigm with the same library can be incredibly beneficial. For example, if you’re using an in-process approach for ASP.NET Core routes, you can at a later time decide to move them out-of-process with some rather minor code changes.

Here’s an example of using Brighter in the exact same fashion as using MediatR. This is simply creating a PlaceOrder object and then using Brighters CommandProcessor to send that request. Brighter will then invoke the PlaceOrderHandler.Handle method and pass the PlaceOrder object you created.

If you’re familiar with MediatR, this is very very similar. And as mentioned, this is still in-process.

In the above example, because we’re throwing an InvalidOperationException, this will bubble up and cause ASP.NET Core to return the client an HTTP 500.


Moving work out-of-process means we’re going to execute the work that needs to be done for a request to an entirely different physical process than where the request originated. Because of this, the work will be done asynchronously.

Here are a couple of simple diagrams of how that looks.


There are two processes, the HTTP Server using ASP.NET Core, and a Message Processor. Both of these are separate .NET Console Apps. The Contracts and Implementation projects are class libraries that are reference by both HTTP Server and Message processor.

When an HTTP Request comes to ASP.NET Core, it invokes the OrdersController and the PlaceOrder route action. Instead of doing the work required then, we will use Brighter to send a message to the message broker (RabbitMQ).

Once the message has been sent to RabbitMQ, ASP.NET will immediately continue and the client will immediately receive the HTTP 204 NoContent that we’re returning.

It will no longer get the InvalidOperationException and an HTTP 500 error. This is because we are not doing that work in-process.

Here’s how the message process works:


Brighter is configured in the Message Processor to receive messages from RabbitMQ. Brighter will receive the PlaceOrder request and then execute the PlaceOrderHandler.Handle passing the PlaceOrder object.

The code change to move from in-process to out-of-process is changing one method.

Instead of calling Send() on the CommandProcessor, we’re calling Post().

That’s it.

Mind you, there’s some configuration required in the ASP.NET Core and the MessageProcessor projects. Here’s a sample of the ConfigureServices in the ASP.NET Core Startup class.

Retries & More

One of the nice things about running out-of-process is having the ability to retry on failures. This is pretty straight forward with Brighter by using a UsePolicy attribute on the handle method.


Brighter has a a lot of features that can be found in their docs.

I realize in this post I have not covered the reasons why or when you should move work out-of-process. I’ll be covering those topics more in future blog posts and videos.

The intent with this post was to display Brighter and how a library that handles both in-process and out-of-process can be very beneficial when you need to make the transition.

If you have any questions or comments, let me know in the comments, Twitter, or YouTube.

Follow @CodeOpinion on Twitter

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

Why use MediatR? 3 reasons why and 1 reason not

Why use MediatR? 3 reasons why and 1 reason not

The MediatR library by Jimmy Bogard has become increasingly popular over recent years, and deservedly so. By its own definition, it’s a simple, unambitious mediator implementation in .NET. Why are so many developers using it? Why should you use MediatR? Here are 3 reasons why you should at least consider using it and one reason why shouldn’t.


Check out my YouTube channel where I post all kinds of content that accompanies my posts including this one regarding MediatR.

What is MediatR?

For those unfamiliar with MediatR library or the mediator pattern:

In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program’s running behavior.

Reason #1: Decoupling

Most examples I’ve seen using MediatR are with ASP.NET Core, but that doesn’t mean that’s the only framework where it’s useful. The point is decoupling your application code from the top-level framework code. Whatever code is actually in charge of executing your code.

Here’s a example using ASP.NET Core MVC

The point is creating a request object that you pass to MediatR which in turn invokes the correct Handler for that request object.

The PlaceOrderHandler has no references to any types or APIs in ASP.NET Core.

Reason #2: Application Requests

The reason why decoupling from top-level framework code such as ASP.NET Core can be important is to ask yourself: Is the application I’m creating an application or a web application?

There’s a difference between a web application and just an application.

An application can have many different inputs. Not all incoming requests are going to be via HTTP. There may be various ways that interact with your application.

For example, you could have recurring jobs that need to perform specific actions at a given time during the day. Or you may also have work that gets triggered from specific messages you’re picking up from a Message Broker.

There are a number of ways that you may want to invoke behaviors in your system that don’t initiate from an HTTP request.

In my example above with ASP.NET Core, we’re ultimately converting an HTTP request into an Application Request. That Application request is entirely decoupled from any specific top level framework and could be invoke from anywhere.

Using MediatR to create application requests to cross an integration boundary.

Reason #3: Request Pipelines

Once you start thinking about application requests, you can go deeper into creating a pipeline for those requests.

If you’re familiar with ASP.NET Core middleware, the purpose is to define a pipeline for an HTTP request.

You can create the same concept using MediatR behaviors. There are a few different ways to create them but here’s an example of a that implements the IPipelineBehavior

When you call mediator.Send() this behavior is called first prior to your primary handler (PlaceOrderHandler). The RequestHandlerDelegate which is a delegate to call PlaceOrderHandler. This allows us to do primary work before calling it or possibly even short-circuiting and not calling it at all, say if we had some validation issues.

This means you could have any number of pre-processors that can be run prior to the primary handler, or post-processors that can be run after.

Why use MediatR

This is incredibly powerful and allows you to separate different concerns related to a given application request.

Why Not?

The reason you may not want to use MediatR is simply that everything is done in-process. Meaning that wherever process is calling mediator.Send() is also the same process that is executing the relevant Handler for that request.

Udi Dahan the founder of NServiceBus posed this question on Twitter with my response.

Why use MediatR

With everything in-process, this becomes really apparent with Events/Notifications (MediatR calls them Notifications).

A notification can have zero or multiple handlers. However the execution of all the notification handlers are done all in the same process.

Why use MediatR

In the example above, if you publish a notification to MediatR, and there are 3 handlers for that notification, it will execute all 3. But what happens if one of them fails and throws an exception?

That exception will bubble up back to where you published the message via MediatR. How do you want to handle this? Can you re-publish that message again and have the handlers that succeeded run again? What if one of them was sending an email?

You want event/notification handlers to be run in independently in isolation. This is where out-of-process messaging comes in.

In this case, you might want to look at NServiceBus, Brighter, MassTransit, Rebus.


If you want more details on how MediatR works, I’ve talked and written about this in my Fat Controller CQRS Diet where I use MediatR as an example on how to decouple your application code from top-level framework code.

Follow @CodeOpinion on Twitter

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.