Sponsorship is available! If you’d like to sponsor CodeOpinion.com and have your product or service advertised exclusively (no AdSense) on every post, contact me.This post is in my Fat Controller CQRS Diet series demonstrating 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. All the source code is available on GitHub. If you’re new to this series, here are earlier posts in this series:
PipelinesIn both the new Query and Commands handlers wrote in prior posts, there was one thing standing out that really didn’t belong. Logging For reference, here was our
AddToCartHandlerthat did some logging at the end of the method. This really isn’t a concern of our
AddToCartHandler. One way we can separate logging out is by having our Command go through another handler after it’s been executed. If we think about this a bit more broad, we can take it a step further and create a pipeline for our Command that can go through various handlers prior and after the main
VideoIf you prefer, I have a video tutorial that follows this blog post.
DecoratorsOne way to accomplish this is to use Decorators. A decorator is nothing more than wrapper around our main handler. In our example, we are going to use StructureMap. In your project.json, add the following dependencies. Next in our Startup.cs we are going to configure StructureMap in the
IServiceProvider ConfigureServices(IServiceCollection)method. The gist is we are going to Decorate/Wrap any
Pipeline<TRequest,TResponse>(which we will create next). Here is our implementation of the
Pipeline<TRequest,TResponse>It will take the primary request as the first argument in the ctor, and then a array of
IPostRequestHandler<TRequest,TResponse>, which we will create next to define our logging handlers.
Log HandlerWe now have everything in place to separate the logging from our
AddToCartHandler. All we need to know is create a class that will implement
IPostRequestHandler<AddToCart,Unit>and it will be invoked after the
AddToCartHandler. Now we can jump back over to our
AddToCartHandlerand remove the
ILoggerand the logging code.