Session handling with RavenDB and ASP.NET MVC
asp.net-mvc, ravendb
Solution
The easiest way is implementing `OnActionExecuting` and `OnActionExecuted` on a base controller and use it.
let's imagine you create your `RavenController` like this:
public class RavenController : Controller
{
public IDocumentSession Session { get; set; }
protected IDocumentStore _documentStore;
public RavenController(IDocumentStore documentStore)
{
_documentStore = documentStore;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
Session = _documentStore.OpenSession();
base.OnActionExecuting(filterContext);
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
using (Session)
{
if (Session != null && filterContext.Exception == null)
{
Session.SaveChanges();
}
}
base.OnActionExecuted(filterContext);
}
}
then all you need to do in your own controllers is inherit from `RavenController` like this:
public class HomeController : RavenController
{
public HomeController(IDocumentStore store)
: base(store)
{
}
public ActionResult CreateUser(UserModel model)
{
if (ModelState.IsValid)
{
User user = Session.Load<User>(model.email);
if (user == null) {
// no user found, let's create it
Session.Store(model);
}
else {
ModelState.AddModelError("", "That email already exists.");
}
}
return View(model);
}
}
Interesting enough, I have found a blog post showing exactly this technique ...
it does explain way more that what I did. I hope it helps you better
Building an ASP.NET MVC app using RavenDB as a Backing Store
Problem
I have a service class UserService that gets an instance of IDocumentStore injected using AutoFac. This is working fine but now I'm looking at code like this: ``` public void Create(User user) { using (var session = Store.OpenSession()) { session.Store(user); session.SaveChanges(); } } ``` Every action that writes to the db uses this same structure: ``` using (var session = Store.OpenSession()) { dosomething... session.SaveChanges(); } ``` What is the best way to eliminate this repetitive code?