Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.This post is in my Fat Controller CQRS Diet series demonstrate how to thin your controllers by implementing commands and queries using the MediatR library. For demonstration, I’m converting the MusicStore application that’s using ASP.NET Core MVC. If you’re new to this series, here are earlier posts in this series:
Simple CommandA command is request to change the state of our domain. The first controller action we are going to rewrite is
ShoppingCartController.AddToCartHere is what the method originally looked like this. As with our simple query, there are a couple things going on here.
- MVC is handling the albumId which is pass as an parameter to the method.
- We do some data access to get the album out of our EF DbContext
- Pass the album to our ShoppingCart
- Return a redirect to the Index action
Extract to CommandWhat we want to extract are the aspects that MVC is handling. From the list above it’s the
AlbumIdbeing passed the URL/Route and then redirecting to the Index action. Everything else is our feature, so let’s extract it into a command. To do so, we need two pieces of information to add to our Request/Command. The
AlbumId. So we will create our Request/Command to contain that data.
Command HandlerNow we can create our handler for this Request/Command. Basically we are going to extract the majority of the code that was inside our Controller Action and put it into our handler. You’ll notice we have our constructor take a couple dependencies on our
Thin ControllerNow we can jump back to our controller and create our
AddToCartRequest/Command and send to the Mediator, which will invoke our Handler.