3

AutoFac を使用して挿入された IDocumentStore のインスタンスを取得するサービス クラス UserService があります。これは正常に機能していますが、今は次のようなコードを見ています。

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

データベースに書き込むすべてのアクションは、次の同じ構造を使用します。

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

この反復コードを排除する最善の方法は何ですか?

4

1 に答える 1

6

最も簡単な方法は、ベースコントローラーに実装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);
    }
}

興味深いことに、まさにこの手法を示すブログ投稿を見つけました...

それは私がしたことよりもずっと多くを説明しています。それがあなたのより良い助けになることを願っています

RavenDB をバッキング ストアとして使用して ASP.NET MVC アプリを構築する

于 2012-06-03T11:39:09.483 に答える