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?

Logging
In the my previous Command Pipeline example, I leveraged StructureMap and the decorator pattern to setup a pipeline. My pipeline would invoke the actual command handler as well as any classes that implemented the correctIPostRequestHandler<TRequest, TResponse>.
This enabled us to create a AddToCartLogHandler
which did our logging that was originally in the ShoppingCartController.AddToCart
action method.
Notifications
Another way to implement this is with a Notification (event). MediatR has this concept built in with a couple interfacesINotification
, IAsyncNotification
The concept and how it works with MediatR very similar as a request (Command or Query) and it’s appropriate handler. The difference with a Notification is it can have many handlers.
- Request: only one handler
- Notification: zero to many handlers
Implementation
I’m going to jump back to our AddToCart command. Instead of it using an IPostRequestHandler<AddToCart, Unit> that I created for our pipeline, I’m going to instead create a notification and publish that notification from MediatR. First, we need to create a class to represent our notification. All the class will contain is a property to specify the AlbumId that was added to the shopping cart. Now we will create a Notification Handler that will accept this new notification object and do the logging. Finally, our last piece is to Publish a newAlbumAddedToCart
notification to MediatR. We can do so in our AddToCartHandler
.
Comments
All the source code for this series is available on GitHub.