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.

Thin Controllers with CQRS and MediatR

MediatRI’m not a fan of fat controllers.

One of the reasons I dislike having my core application logic in controllers is because I like using the web frameworks for what they are good at in my context.

My context is usually creating web api’s.

For me I use web frameworks as infrastructure that handles

  • HTTP routing and endpoints
  • Deserialization of input payloads
  • Serialization of output payloads
  • HTTP Headers and Status Codes
  • Web Stuff (eg File Uploads)

You get the gist, I like using it for handling the web.  Not for containing my features.

If you have any questions, please follow me on Twitter.

Follow @CodeOpinion on Twitter

Thin Controllers

The way that I remove any of my feature code from my controllers is thru commands and queries.

If you are familiar with CQRS, then this will make sense.  But I’m not talking about Event Sourcing, Domain Driven Design, or having multiple data stores or any of the overly complex version people think it is.

I’m simply talking about splitting up incoming requests into commands and queries.

Starting with CQRS, CQRS is simply the creation of two objects where there was previously only one. The separation occurs based upon whether the methods are a command or a query (the same definition that is used by Meyer in Command and Query Separation, a command is any method that mutates state and a query is any method that returns a value). – Greg Young

This is pretty straight forward.  I’d guess most actually apply CQRS without really knowing it most of the time.

Repositories

I’m also not a a fan of fat repositories.

They generally end up as a giant low cohesive classes full of data access code that is used in one place.

Commands & Queries

I’ve previously posted about using Query Objects instead of Repositories.  The same applies for commands.

We will create a message (class) that will represent the command/query we want to execute.  The message will contain the arguments needed for processing the message.

In essence it’s like taking the parameters of a method and turning it into a class.

In order to facilitate mapping and handling the execution of command and queries,  I use the MediatR.

MediatR

Simple mediator implementation in .NET

In-process messaging with no dependencies.

Supports request/response, commands, queries, notifications and events, synchronous and async with intelligent dispatching via C# generic variance.

Command

Let’s take a look at a simple command for changing the pricing level of our customer.

Pretty straight forward.  It contains the minimum amount of data needed in order for us to perform the given task.

Handler

Now we will create a handler for this command message.

Now all that is left is to wire up our command to our web framework.

Controller

In this example I’m using NancyFX which uses Modules instead of Controllers.  This shouldn’t be too hard to translate if you are more familiar with Web Api.

More…

Here are some more helpful posts in regards to create commands, queries and MediatR.

How about you?

Do you apply a similar pattern as well? I’d love to hear about other implementations or uses.  Comment below or follow me on twitter.

Follow @CodeOpinion on Twitter

Couchbase Linq Provider

Couchbase

I recently decided to use Couchbase for a personal side project.  The primary reason I chose to use it was because I hadn’t yet.  Simple as that.

Again, this is for a personal side project where I try out different technologies.  The second reason was I was interested in N1QL (pronounced “nickel”) which is the Couchbase Server query language.

I’m not covering installing the Couchbase server.  if you don’t have a Couchbase server installed, check out the offical docs.

Couchbase .NET SDK

The most obvious route for accessing a Couchbase server is by using the the official Couchbase .NET Client.  Looking at the docs, its very simple to store and retrieve a documents.  However, one of the features I was most interested was if it had a Linq provider.  It does not.  Bummer.

Linq2Couchbase

Thankfully I discovered Lin2Couchbase by Couchbase Labs which is a Linq provider to produce N1QL using the official Couchbase .NET SDK.

Grab the NuGet Package

Install-Package Linq2Couchbase

Owin/Katana

My side project is a web app that is self host using Katana and NancyFX.  In order to initialize the Couchbase client, you can use the ClusterHelper in your Startup class.  The reason it is done here is that the it is only required be initialized once.  The cluster helper will create a Cluster object which will later be used to create a BucketContext.

BucketContext

If you are familiar with Entity Framework, the BucketContext from Linq2Couchbase is similar to a DbContext.  It provides an API for querying a Couchbase bucket.

You can now inject IBucketContext into your Nancy Modules or Controllers if using ASP.NET MVC/WebAPI.

Registration

Whichever DI container you are using, you will want to register IBucketContext.  I’m using Unity and my registration as follows.

 POCO

For this example, I’ve created a simple User class.  One important thing to note is that you must specify which property in your class is the key.  You can do so by adding the KeyAttribute.  Also, the Key must be a string.

Save

Adding a new object is pretty straight forward.   Just pass your new object the Save() method on the IBucketContext.

Querying

Using the BucketContext you can query your bucket which is also very straight forward.

Note: If you have just installed Couchbase, you must create a primary index on the bucket you are querying.  Refer to the documentation on how to do so.  This stumbled me a bit at the beginning.  Thankfully the Brant Burnett was kind enough to help me out.

Documentation

The GitHub page for Linq2Couchbase has a ton of goodness.  I highly recommend checking it out if you are interested in couchbase or are looking for linq support.

As of this post, the project looks very active (just recently adding async support) and hopefully I can contribute back.


Event Store Persistent Subscriptions Demo

Event Store Persistent SubscriptionsIn my previous blog post, I talked about Catch-Up Subscriptions in-comparison to Persistent Subscriptions in Event Store.

I’ve been meaning to create a little demo as I didn’t find very much in my limited searching.

Specifically, I wanted to create a console app that would contain the subscription client  and another console app (event writer) that would write events to a stream.

This way you could run the subscription client multiple times, then run the event writer and see how the events are only received from one subscription client.

Source

All the source code for this demo is available on GitHub.  Please take a look to follow along as the rest of this post is describing how it works.

Although I’ve added this to as a new repo on GitHub, It is also available in the EventStore.Samples.DotNet repo on GitHub along with other subscription model examples.

Server

If you don’t have it already, download a copy of Event Store and run EventStore.ClusterNode.exe with default arguments.

This will start the Event Store server under port 1113.  The web UI will be accessible via http://localhost:2113

Create Subscription

First you need to create a subscription to a stream.  You will also provide a group name which you will also use when connecting to the subscription.

In my demo I’ve included code to create the subscription.  This is simply because I don’t want anyone running the demo to have to create it manually. The documentation discourages it from being created in your general application code.

Normally the creating of the subscription group is not done in your general executable code. Instead it is normally done as a step during an install or as an admin task when setting things up. You should assume the subscription exists in your code.

The web UI has a pretty nice interface for viewing your subscriptions as well as creating and updating them.

Event Store

Connecting to Persistent Subscription

When connecting to a persistent subscription, you must specify the stream and the group in which you use to create the subscription.

There are two other optional parameters which I’ve found to be important: bufferSize and autoAck

bufferSize: The number of in-flight messages this the server will send to the client.

autoAck: The client API will automatically acknowledge after the EventAppeared method returns.  If an exception is thrown in the EventAppeared method, the subscription will drop your subscription.

Dropped Subscription

I found it helpful to have the subscription reconnect when it is dropped.

Another case where the subscription can be dropped is if changes to the subscription are made from another client or the web UI.

EventAppeared

Method is invoked once the subscription receives an event. As you can assume the ResolvedEvent contains the event and the eventStoragePersistentSubscriptionBase allows you to acknowledge or not acknowledge (fail) a ResolvedEvent or a array of ResolvedEvents.  If you have autoAck then you do not need to acknowledge.

Running Demo

To run the demo, simply build the solution to generate the exe’s.

Run multiple instances of PersistentSubscription.exe

Multiple instances will allow you to see how each will connect to the subscription and only receive one of the events that is written to the stream.

consumer

You can also now see in the Web UI that there are two connections.

Connections

Now if you run the WritingEvents.exe it will write 100 events to the stream.

The PersistentSubscription.exe will now have received the events.  But only one event will be sent to a client.  you can see that as our subscription is setup for Round Robin.

Results

Results

Source Codegithub-octocat

The source code for this demo is available on GitHub.