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:
In both the new Query and Commands handlers wrote in prior posts, there was one thing standing out that really didn’t belong.
For reference, here was our
AddToCartHandler that 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
If you prefer, I have a video tutorial that follows this blog post.
One 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
ICancellableAsyncRequestHandler<TRequest,TResponse> in a
Pipeline<TRequest,TResponse> (which we will create next).
Here is our implementation of the
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.
We now have everything in place to separate the logging from our
All we need to know is create a class that will implement
IPostRequestHandler<AddToCart,Unit> and it will be invoked after the
Now we can jump back over to our
AddToCartHandler and remove the
ILogger and the logging code.
Validation, Authorization, Whatever
Hopefully now you can see that we could extend this to have pre-handlers that may do data validation, authorization or whatever other responsibilities that probably shouldn’t be in your main handler.
All the source code for this series is available on Github.
If have another way of creating a pipeline or separating concerns from your handlers, please leave comment or let me know on twitter.