最简单的方法是在基础控制器上实现OnActionExecuting
和OnActionExecuted
并使用它。
让我们设想你创建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
我看过类似的指令(在ravendb教程的地方),但我想这样的逻辑转移到我的服务层,我想这不应该成为我的控制器的一部分。 – b3n
然后以相同的方式在您的DLL中实现它。我在我的Repository层上使用它,但之前我总是使用缓存层。 – balexandre
我该怎么做?在我的服务类中,我没有可用的ActionExecuting和ActionEcecuted。 – b3n