Created
August 8, 2012 19:26
-
-
Save thefringeninja/3297884 to your computer and use it in GitHub Desktop.
Raven + Nancy Pipeline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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