Click here to Skip to main content
13,867,109 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


13 bookmarked
Posted 6 Dec 2018
Licenced CPOL

Dive into Microservices Architecture - Part III

, 6 Dec 2018
Rate this:
Please Sign up or sign in to vote.
How to use NancyFx to build a Microservice


The first part of this article discussed the Microservice Architecture (MSA) in detail and tried to explain the basic terminology of MSA and its concepts. The second part discusses the OWIN Framework with an example that showed how to use it. This part will discuss NancyFx and will try to give a glance into the usage of this framework in the building of MSA based services. Before you start reading this part, I suggest you to read Part I if you do not have any background about MSA.


As we discussed in the second part, there were several problems involved in the direct use of web servers like IIS, Apache, or HTTP.sys (in the case of having a stand-alone service), such as platform dependency, limited concurrent connections in the kernel level, and etc. For more information, you can read more in the Background of the second part.

We also discussed very briefly why the Windows Communication Function (WCF) was not really successful in separating web applications from the web servers and how OWIN Framework made this possible by introducing standard interfaces between web servers and web applications. We also mentioned how RESTful services are easily implementable in the context of OWIN than WCF.

In this part, I will continue the topic by introducing a new framework called NancyFx, I personally found it a very sexy framework just as Nancy herself! However, there are certain things that seem to be difficult to accomplish with Nancy where they work out of the box in MVC with OWIN, like DryIoc, swagger, property injection. This could be a serious backdraw about it.

What is NancyFx?

Developers of Nancy says that "Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .NET and Mono. The goal of the framework is to stay out of the way as much as possible and provide a super-duper-happy-path to all interactions". I would not add anything more on this definition as it is exactly how they described. I personally found the use of Nancy very handy and less complicated. Nancy is designed as a Domain-Specific Language (DSL) for handling DELETEGET, HEAD, OPTIONS, POST, PUT, and PATCH requests.

Nancy provides a very easy way to create HTTP based services. It allows you to create service and start communicating over HTTP protocol with almost zero configuration effort in your project. It supports several contents such as JSON, HTML, XML, and a plain text.

What Does Mean Domain-Specific Language?

Domain-Specific Language is a computer language which is designed for a particular domain in contrast to a General-Purpose Language (GPL) like C, Java, XML, UML, etc. However, the line between these two is not always sharp.

Hosting Nancy

Nancy can be hosted with ASP.NET, with WCF, with Azure, Suave.IO, OWIN, Web (Katana), Self Hosting, Umbraco, and with Nginx on Ubuntu.

NancyFx vs ASP.Net Core Web API

It is important to understand really what is Nancy and when it can be used. To learn something better always comparing it with similar technologies is an easy way. So I decided to compare Nancy with ASP.NET MVC and WebApi to show the advantages of Nancy very briefly.

Table 1: NancyFx vs Web API

ASP.NET Core Web API NancyFx
Used widely by developers for developing RESTful applications on top of .NET Framework. Open source and lightweight framework for building HTTP based services on top of .Net Framework.
Must configure properly before developing HTTP-based services. Emphasizes on sensible and default setup. Means that developers can start using Nancyfx without dealing with a complex configuration.
Uses convention based routing mechanism, in other words, it uses MVC routing mechanism to route HTTP requests. It allows defining routes in the constructors of a module by specifying a Method + Pattern + Action + (optional) Condition.
Uses the HTTPclient to interact with varied applications and clients. It is designed with hosts that act as a hosting environment.
Can be hosted by IIS and other web servers supporting .NET 4.0+ or even as a self-hosted framework. Can be hosted by varied environments without dependency on any specific framework.
Web API is built on top of ASP.NET. It communicates with the Web API server through the HTTPclient. Developed using .NET Framework client profile. However, it contains its own request and response objects.

NancyFx Hello World

Now it is time to put our hands on NancyFx and see how to use it. Before downloading the source from the repository, you need to bear in mind that the following NuGet Packages need to be restored/re-installed on the project after opening it (usually, Visual Studio should take care of this part).

Nancy                               {1.4.5}
Nancy.Hosting.Self                  {1.4.1}
Nancy.Owin                          {1.4.1}
Owin                                {1.0}  

Otherwise, you can install them from PM Console or Nuget Package Manager.

Using the Code

The following part will explain the use of three prominent classes called Startup, NancyModule, and Program, that are involved in keeping the service up and running over the NancyFx Framework.

Configure NancyFx for Self-Host

Here is where NancyFx relies on the OWIN in order to use the AppBuilder (implementor of the IAppBuilder interface). The following code is presenting configuration.

using Owin;

public class Startup
    public void Configuration(IAppBuilder app)

As you can see, you only need to use the Owin.dll in to build your Nancy self-hosted Startup. It will be interesting if you compare this part with the OWIN Framework Web API configuration.

Add a Nancy Module

According to the official website of Nancy, "Modules are the one thing you simply cannot avoid because they are where you define the behavior of your application." In other words, module in NancyFx does the same thing that API Controller does in OWIN Framework. To create a module, you need to inherit it from the NancyModule class.

The following code will define to different behavior of GET and one POST. In the previous part, we already implemented and tested them. The first GET will return a string array, the second GET will return a proper value according to what you give on the GET request, and the POST will receive data from the body and will translate it into a string by using an extension method from the Nancy.Extensions class.

using Nancy;
using Nancy.Extensions;
using System;

namespace NancyFxMicroservice
    public class HelloWorldModule : NancyModule
        public HelloWorldModule():base("api")
            Get["/values"] = parameters => new string[] { "Hello", "World", "...!" };
            Get["/values/{id}"] = parameters => ( == "1") ? 
            "Hello" : ( == "2") ? "World" : ( == "3") ? 
            "...!" : "No world found... ;-)";
            Post["/values"] = _ => 
                var value = Context.Request.Body.AsString();
                Console.WriteLine($"The received value is:{value}");
                return HttpStatusCode.OK;

Call Service

To call service, we first need to define the Program.cs class in a way that will run the service on a specific URL which in this case is: http://localhost:9000.

using System;
using Nancy.Hosting.Self;

namespace NancyFxMicroservice
    class Program
        static void Main(string[] args)
            using (var host = new NancyHost(new Uri("http://localhost:9000")))
                Console.WriteLine("Running on http://localhost:9000");

Then exactly like the previous part, we can use Postman to send HTTP, GET, and POST requests to the service and see the results on the console or debug window. Follow the steps mentioned in the previous part and test your service.

Go to Previous Part


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Aydin Homay
Software Developer (Senior) BHGE
Germany Germany
Aydin Homay worked as software engineer and researcher in different countries with a wide range of related projects and engineers from all around the world. He was involved in Oil&Gas, Telecommunication, Railway and Semiconductor projects and played various roles such as junior, senior, and lead engineer both in embedded and non-embedded devices and technologies.

During his professional carrier, he was directly involved in designing and maintaining editor, compiler, and interpreter for IEC 611131-3 (PLC programming standard) and fault-tolerant communication layer for distributed automation standard IEC 61499, and many other projects such as DCS (Distributed Control Systems), (SCADA) Supervisory Control and Data Acquisition System, Oilfield (CMS) Computerised Maintenance Systems, Oil&Gas Laboratory Automaton Systems, and Semiconductor Equipment Connectivity Solutions.

Currently, Aydin Homay pursues a Ph.D. degree in the field of Industrial Communications with the focus on flexible industrial automation and control systems at the Computer Science Faculty, in the Technical University of Dresden and works as a software engineer at the PEER Group GmbH and Infineon Technologies AG., Dresden, Germany.

Aydin`s main research and work areas are Industrial Communication and Automation Systems, Real-Time Systems, Service-Oriented Systems, IEC 61131-3, IEC 61499, and Distributed Embedded Systems.

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 6 Dec 2018
Article Copyright 2018 by Aydin Homay
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid