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.
I’ve previously blogged about Nancy.Linker
, the URI Builder for NancyFX. However, I wanted to take it a step further and give an actual example of how I handle linking to Nancy routes through my application.
Organize by Feature
I organize my application by features
. Features are generally commands or queries. They are either returning data (queries) or actions that represent behaviors (commands).
This means that I generally only have one route per feature. Since I organize by feature, this means that I put the Nancy module with the single route and then all subsequent code (commands or queries, handlers, models) in that same file.
Here is an example of a single feature, which is to change the pricing level of a customer.
If you are creating a HTTP API or using MVC rendering a view, you are in the same situation: How can I create a URL to this route?
The first step is going to be creating a new Route class which will contain the route name and path. We will use this same Route class when defining our route in the Nancy module, as well as when creating the link using Nancy.Linker.
Next we are going to create a wrapper around IResourceLinker from Nancy.Linker. The reason being is that IResourceLinker methods to build a URI require the NancyContext. In my example above, since I’m using MediatR to handle commands and queries, I need wrap the IResourceLinker along with the NancyContext.
Here is the registration of the RouteLinker and IResourceLinker in the Nancy Boostrapper with our container (TinyIoC).
Now let’s revisit our feature ChangePricingLevel. Previously we did not yet have a name on our route and we had the path of the route directly in the NancyModule’s RouteBuilder.
We are going to update this to use our new Route class to define this route, and then use that Route in the NancyModule’s RouteBuilder. Also, we are now going to create an extension method to our RouteLinker which will return the route for the ChangePricingLevel feature.
Now when we want to get the route for the ChangePricingLevel feature, we can use the extension method on the RouteLinker. This also enables us to make sure all the appropriate parameters are defined when creating the route.
Let’s create another feature for returning our customer’s name along with the link to the ChangePricingLevel.
Now when we run our application and fetch our customer, here are the links generated.
The source code
for this demo is available on Github.
Let me know if you are using another approach to generating URIs and routes with Nancy. Please share in the comments below or on twitter.