Session-per-request with Nancy

Session-per-request is a common model for session management (although there are some good arguments against using it!).

There are many ways of implementing it, from Ayende’s base controller to (N)Hibernate’s contextual sessions.

Recently I’ve got into the habit of leaning on the container, and registering a session per-web-request. By default, Nancy uses TinyIoC, which doesn’t support per-web-request registrations (there is an extension available, but it won’t be required).

What Nancy offers instead, is a chance to customise the child container that will be used for the request:

public class Bootstrapper : DefaultNancyBootstrapper
{
    private readonly ISessionFactory sessionFactory;

    public Bootstrapper()
    {
        this.sessionFactory = SessionFactoryFactory.BuildFor("ConnStringName");
    }

    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
    {
        base.ConfigureRequestContainer(container, context);

        container.Register((c, o) => this.sessionFactory.OpenSession());
    }
}

Which means your module can happily take a dependency on ISession.

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