Quantcast
Viewing latest article 12
Browse Latest Browse All 55

Fat Controller CQRS Diet: Notifications

Image may be NSFW.
Clik here to view.
CQRS Notifications
This post is in my Fat Controller CQRS Diet series. It demonstrates how to thin your controllers by implementing commands and queries using the MediatR library.

I’m converting the MusicStore application that’s using ASP.NET Core MVC.   All the source code is available on GitHub.

If you’re new to this series, here are earlier posts to get up to speed:

  1. Overview of Series
  2. Simple Query
  3. Simple Command
  4. Command Pipeline

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 correct IPostRequestHandler<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 interfaces INotification, 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.

View the code on Gist.

Now we will create a Notification Handler that will accept this new notification object and do the logging.

View the code on Gist.

Finally, our last piece is to Publish a new AlbumAddedToCart notification to MediatR.  We can do so in our AddToCartHandler .

View the code on Gist.

Comments

All the source code for this series is available on GitHub.Image may be NSFW.
Clik here to view.
GitHub

Which do you prefer, Pipeline or notifications? Let me know in the comments or on Twitter.


The post Fat Controller CQRS Diet: Notifications appeared first on CodeOpinion.


Viewing latest article 12
Browse Latest Browse All 55

Trending Articles