Over the last cou­ple of days I’ve been play­ing around with Nancy, one of a num­ber of micro web frame­works now avail­able for the .Net plat­form. You can read more about Nancy on their github readme page but in short it’s an ultra light­weight, eas­ily exten­si­ble frame­work that lets you run a HTTP web server in a num­ber of host­ing envi­ron­ments (IIS, WCF, or inside a sim­ple con­sole app) and can inte­grate with a num­ber of view engines (Razor, Spark, NDjango, etc).

Protobuf-net on the other hand, is Marc Grav­ell’s .Net imple­men­ta­tion of Google’s Pro­to­col Buffer mes­sag­ing for­mat, which as I have shown, is over 10x faster than the BCL’s Bina­ry­For­mat­ter!

Get­ting Started

If you’re not famil­iar with how Nancy works, I’d rec­om­mend tak­ing half an hour or so and go through the doc­u­men­ta­tions first.

Dese­ri­al­izer

On the dese­ri­al­iza­tion side, Nancy sup­ports JSON and XML bind­ing out of the box, to add pro­to­col buffer sup­port to the equa­tion all you need to do is to cre­ate a class that imple­ments the IBody­De­se­ri­al­izer inter­face and the Nancy boot­strap­per will take care of the rest (it auto reg­is­ters all the imple­men­ta­tions of the rel­e­vant inter­faces at startup).

How­ever, if there are more than one imple­men­ta­tion of IBody­De­se­ri­al­ize defined in the loaded assem­bly which can dese­ri­al­ize the con­tent type application/x-protobuf then at run­time the dese­ri­al­izer will be cho­sen at random.

Seri­al­iza­tion

To seri­al­ize the response body with protobuf-net, all you need to do in the han­dler is to return a Response object and seri­al­ize the object you want to return like this:

Alter­na­tively, you can cre­ate a sub­type of Response and take in the object you want to use as the response body and auto­mat­i­cally seri­al­ize it, some­thing along the line of:


Source Code

You can down­load the source code for the demo app here, there’s also a sim­ple unit test using Nancy.Testing helper framework.

Share