Integrating Nancy with protobuf-net

Over the last cou­ple of days I’ve been play­ing around with Nan­cy, one of a num­ber of micro web frame­works now avail­able for the .Net plat­form. You can read more about Nan­cy on their github readme page but in short it’s an ultra light­weight, eas­i­ly exten­si­ble frame­work that lets you run a HTTP web serv­er 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, NDjan­go, etc).

Pro­to­buf-net on the oth­er 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!

Getting Started

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


On the dese­ri­al­iza­tion side, Nan­cy 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­iz­er inter­face and the Nan­cy 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 start­up).

How­ev­er, 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 appli­ca­tion/x-pro­to­buf then at run­time the dese­ri­al­iz­er will be cho­sen at ran­dom.


To seri­al­ize the response body with pro­to­buf-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­tive­ly, 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­cal­ly 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 frame­work.