Created
March 9, 2012 12:27
-
-
Save rdingwall/2006319 to your computer and use it in GitHub Desktop.
RavenDB ASP.NET Web API session management
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 class BooksApiController : FooApiController | |
{ | |
public IEnumerable<Book> Get() | |
{ | |
return DocumentSession | |
.Query<Book>() | |
.OrderByAscending(p => p.Author) | |
.Take(100); | |
} | |
} |
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 abstract class FooApiController : ApiController | |
{ | |
public IDocumentSession DocumentSession { get; set; } | |
} |
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
// or self-hosted startup | |
public class MvcApplication : HttpApplication | |
{ | |
protected void Application_Start() | |
{ | |
... | |
var config = GlobalConfiguration.Configuration; | |
config.Filters.Add(new RavenDbApiAttribute(documentStore)); | |
} | |
} |
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 class RavenDbApiAttribute : ActionFilterAttribute | |
{ | |
readonly IDocumentStore documentStore; | |
public RavenDbApiAttribute(IDocumentStore documentStore) | |
{ | |
if (documentStore == null) throw new ArgumentNullException("documentStore"); | |
this.documentStore = documentStore; | |
} | |
public override void OnActionExecuting(HttpActionContext actionContext) | |
{ | |
var controller = actionContext.ControllerContext.Controller as FooApiController; | |
if (controller == null) | |
return; | |
controller.DocumentSession = documentStore.OpenSession(); | |
} | |
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) | |
{ | |
var controller = actionExecutedContext.ActionContext.ControllerContext.Controller as FooApiController; | |
if (controller == null) | |
return; | |
controller.DocumentSession.Dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where do you get documentStore from in application_start ?