Fat Controller CQRS Diet: Simple Query

Simple QueryThis is a series of blog posts that 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.

For more information on the purpose of this series, check out my initial post.

Follow Along

You can get all the code for this entire series on on my fork of the MusicStore app GitHub.   If you have any improvements or suggestions, please create an issue or send a PR and I’ll be sure to include it in any of my blog posts.

Simple Query

For our first example, we are going to rewrite the HomeController Index action.  I figured it’s a the entry point into our app, so no better place to start.

What is also helpful in this example is it is fairly straight forward.  It contains some data access and in-memory caching prior to do view rendering.

Here’s what it looks like.

MediatR

There are a couple packages we need to add to our project.  We are going to be using MediatR as mentioned, however we are also going to add another package “MediatR.Extensions.Microsoft.DependencyInjection” by Jimmy Bogard (creator of MediatR).  This will scans assemblies and adds handlers implementations to the container.

Your project.json dependencies section should look as follows

Register MediatR

In our Startup.cs we need to register mediator in our ConfigureServices method.  The “MediatR.Extensions.Microsoft.DependencyInjection” added an extension method “AddMediatR” which we can now call to register all our handlers we will be created.

Add the following in the ConfigureServices method

Query Message

One of the ways I’ve explained Mediator pattern is like the post office (snail mail).  When you want to send a message to someone, you send it to the post office and they route it to the physical location for that message.  You don’t need to know how or where that location is, all you care about is giving it to the post office and let them do the work.

Instead of making a method call we are interchangeably going to create a message (object) and send it to the Mediator and have it figure how to create the appropriate handler and it dependencies and then invoke the handler.

Since our Home/Index method doesn’t require any parameters, our message is going to be pretty straight forward.

What we are doing is defining a class that implements IAsyncRequest.  The first type parameter defines the return value from our handler.  Meaning, when we send that message to the mediator what type do we expect in return.

Handler

Now we need to implement our handler.  Our handler will accept the the message (Home) and return a List<Album>.  What you will notice is I’ve for the most part taken the code from the controller and moved it to this handler.

Dependencies

One thing to notice is that our Handler’s constructor is taking dependencies (EF Context, Cache, AppSettings) that were originally defined in the Index method using dependency injection.

Thin Controller

Now let’s go back over to our HomeController and use MediatR.

First thing we will do is inject the IMediator into the HomeController via the constructor.  Then we will be calling MediatR with our Home message to get our list of albums.

Next

That’s a very simple query endpoint that we moved our logic to a Query Handler using MediatR.

Next up we we will handle a command.

If anyone has any comments, suggestions or recommendations please leave comment or let me know on twitter.


Why use Nancy?

NancyFXOn one of my posts showing how you can use Nancy with ASP.NET Core, David Anderson posted the following comment

I came across some Nancy blogpost last week and got curious about it and so looked on internet for more information. I wanted to know why should someone use Nancy and why plain asp.net core is not sufficient. So far every place I look I see the same introduction, you know that one with ‘…super-duper-happy-path…’. But to be honest it’s still not clear ‘why’? What is it that someone can not do in ASP.NET Core which is ‘super-duper’ in Nancy? What is hard or missing in ASP.NET Core which is easy or available in Nancy? The need of such a framework on top of ASP.NET Core is very vage to me.

I realized that I never really blogged about why I started using Nancy.  I hinted at it slightly in my post about ASP.NET Core MVC Attribute Routing, but not in much detail.

MVC & Web API Routing

Like most, I primarily used ASP.NET MVC and Web API.  When I got into creating more Web API’s, the first thing that started causing me trouble was routing.

The convention based routing employed is to define your routes in the RouteCollection.  This is the familiar default route that you might have used before.

The primary issue I had with defining routes and route templates up front, was I to defined them closer to the code that was actually executing at a given endpoint.

Route Attributes do ultimately solve this problem and from what I’ve read recently, this seems to be the common way most now define routes.  However, I’m simply not a fan of attributes in this situation.  I won’t get into the reasons why, as I don’t think starting an attribute war serves much purpose for this post.

Nancy Routes

When I first seen how you defined routes in Nancy, I realized it was exactly what I was looking for.

Routes are defined in the constructor of a module. In order to define a route in Nancy, you need to specify a Method + Pattern + Action + (optional) Condition.

They’re just endpoints…

When you look at a Nancy module, you could compare it to a MVC or Web API Controller, but it’s really nothing more than a place you can define HTTP Endpoints.

This means you can use Modules as Controllers and develop using your familiar MVC pattern, or you could use them as Web API’s.  You can have your endpoint do whatever you need and return whatever you want.

Simple

Nancy by default is really simple to use.  You need zero configuration to get started.  Zero.

Add a Nancy Module and you are off to the races.

I’ve made a couple different posts on how you can use Nancy along side Web API in ASP.NET 4, and how you can use it with ASP.NET Core.

ASP.NET Core

Back to the comment and the last sentence:

The need of such a framework on top of ASP.NET Core is very vage to me

Nancy doesn’t replaces ASP.NET Core, but it could replace your need for ASP.NET Core MVC.

With the application pipeline (middleware) in ASP.NET Core, this allows you to leverage many different components that serve different purposes all within your web application.

For example you could use Nancy, ASP.NET Core MVC, Static File Server and Authentication.

More Reasons

There are many more reasons and many considerations. I highly recommend reading a post by Jonathan Channon that covers different aspects.  The post that’s a tad old, but still very relevant.

I really enjoy the conversation I get in some of the comments.  Please leave a comment here or on twitter.


ASP.NET Core MVC Attribute Routing

Over the last several years, I haven’t done much work with ASP.NET 4 MVC.  I primarily have used ASP.NET Web API and then eventually went full on with Nancy.

My main reason for switching to Nancy for creating Web API’s was I wasn’t overly fond of the ASP.NET MVC/WebAPI Routing.   I really liked how you you defined routes in Nancy by specifying the route in the constructor of your Module/Controller which was close to the Action.

I tweeted this yesterday, and it seems I’m not alone.

Attributes

I can’t say I’m a fan of attributes, that’s another blog post entirely, so I wont get into here.  But based on my current understanding of ASP.NET Core MVC, you can use Route attributes closer to the action.  So for my own experimenting, let’s give this a try and see how well it can work.

Demo

For reference, I’m using the ASP.NET Core Web API Template that comes with Visual Studio 2015.  All the source code for this blog post is on GitHub.

If we look at the ValuesController, it defines the base route as being “api/[controller]”.

If we translate this, we can make an HTTP call to  http://localhost:5000/api/values which should call the Get() method returning an string array.

result1

Custom Action

Now let’s say I want to create a new method and define it a specific route “api/values/getmore” which should call the GetMoreStuff() method.

My first beginner thought was to specify a Route attribute on the action/method.

result2

As you can see, it’s actually calling the Get(int) method and returning “value” rather than calling GetMoreStuff().

This is because the route attribute on the Get(int) HttpGet attribute is defining the route that is taking over.  Let’s change this a bit since I know know that the  HttpGet attributes first argument is the route template.

result3

Huzzah! The results we expected.  However I’m not in love with the controller having the Route attribute to define the prefix to our route.  Let’s get rid of it and define routes per action/method.

result4result5

Closer to the Action

This definitely puts our routes closer to the action, however I’m still not in love with attributes.

Let me know if you have any other options for defining routes closer to the action, but more specifically, in code.