Creating a standalone Nancy server

Something I tend to be doing more often, is creating a standalone Nancy server and with each of them, I setup a lot of the same boilerplate code. So I thought I would put together what that setup looks like and throw the code up on GitHub.

This is an opinionated setup using the following packages: Nancy, Autofac, Serilog, ConfigInjector

Getting Started

Starting with a new empty web application in Visual Studio 2015:

image

Then add the initial nuget packages:

Install-Package Nancy.Hosting.Aspnet

Install-Package Nancy.Bootstrappers.Autofac

Next, implement the Autofac Bootstrapper for Nancy by adding a class called Bootstrapper.cs and implement the AutofacNancyBootstrapper:

    public class Bootstrapper : AutofacNancyBootstrapper
{
protected override void ConfigureApplicationContainer(ILifetimeScope existingContainer)
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyModules(Assembly.GetAssembly(typeof(Bootstrapper)));
builder.Update(existingContainer.ComponentRegistry);
}
}

Finally create a NancyModule class for the endpoint:

    public class SampleEndpoint : NancyModule
{
public SampleEndpoint() : base("/sample")
{
Get["/"] = _ => GetSampleData();
}

private Response GetSampleData()
{
return "hello world";
}
}

Now if you run up the application, and navigate to the sample endpoint, you should get the hello world response.

image

In the next post I’ll add some logging.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: