使用RavenDB和ASP.NET MVC进行会话处理

b3n*_*b3n 3 asp.net-mvc ravendb

我有一个服务类UserService,它获取使用AutoFac注入的IDocumentStore实例.这工作正常,但现在我正在看这样的代码:

public void Create(User user)
{
    using (var session = Store.OpenSession())
    {
        session.Store(user);
        session.SaveChanges();
    }
} 
Run Code Online (Sandbox Code Playgroud)

写入db的每个操作都使用相同的结构:

using (var session = Store.OpenSession())
{
    dosomething...
    session.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

消除这种重复代码的最佳方法是什么?

bal*_*dre 6

最简单的方法是实现OnActionExecutingOnActionExecuted基本控制器上,并使用它.

让我们想象你创建RavenController这样的:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你需要在你自己的控制器中做的就是继承RavenController像这样:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,我发现一篇博文正好展示了这种技术......

它确实解释了我所做的更多.我希望它能帮到你更好

使用RavenDB作为Backing Store构建ASP.NET MVC应用程序