Skip to content

Instantly share code, notes, and snippets.

@thefringeninja
Created August 8, 2012 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thefringeninja/3297884 to your computer and use it in GitHub Desktop.
Save thefringeninja/3297884 to your computer and use it in GitHub Desktop.
Raven + Nancy Pipeline
public static class RavenPipelineExtensions
{
public static void EnableRaven(this IPipelines pipelines, IDictionary<string, IDocumentStore> documentStores,
string ravenSessionKey)
{
documentStores.Keys.ForEach(
database =>
{
var key = ravenSessionKey + "." + database;
var documentStore = documentStores[database];
pipelines.BeforeRequest.AddItemToStartOfPipeline(
context =>
{
context.Items[key] = documentStore.OpenSession();
return null;
});
pipelines.AfterRequest.AddItemToEndOfPipeline(
context =>
{
dynamic session;
if (false == context.Items.TryGetValue(key, out session) || session == null)
{
return;
}
using (session)
{
// if you return an error code and you really want raven to save you need to do it yourself.
if ((int)context.Response.StatusCode >= 400)
{
return;
}
session.SaveChanges();
}
});
pipelines.OnError.AddItemToEndOfPipeline(
(context, _) =>
{
dynamic session;
if (context.Items.TryGetValue(key, out session) && session != null)
{
session.Dispose();
}
context.Items[key] = null;
return null;
});
});
}
public static IDocumentSession RavenSession(this NancyContext context, string key = null)
{
return (IDocumentSession)context.Items["ravendb.session." + (key ?? Bootstrapper.DefaultRavenDatabase)];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment