2012-06-03 91 views
3

我有一个服务类UserService,它获取使用AutoFac注入的IDocumentStore实例。这是工作的罚款,但现在我看这样的代码:使用RavenDB和ASP.NET MVC处理会话

public void Create(User user) 
{ 
    using (var session = Store.OpenSession()) 
    { 
     session.Store(user); 
     session.SaveChanges(); 
    } 
} 

写入到数据库的每个操作使用此相同的结构:

using (var session = Store.OpenSession()) 
{ 
    dosomething... 
    session.SaveChanges(); 
} 

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

回答

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); 
    } 
} 

那么所有你需要在你自己的控制器要做的就是从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); 
    } 
} 

足够有趣,我发现了一篇博文,详细展示了这种技术......

它确实解释了我所做的更多。我希望它可以帮助您更好地

Building an ASP.NET MVC app using RavenDB as a Backing Store

+0

我看过类似的指令(在ravendb教程的地方),但我想这样的逻辑转移到我的服务层,我想这不应该成为我的控制器的一部分。 – b3n

+0

然后以相同的方式在您的DLL中实现它。我在我的Repository层上使用它,但之前我总是使用缓存层。 – balexandre

+0

我该怎么做?在我的服务类中,我没有可用的ActionExecuting和ActionEcecuted。 – b3n