NHibernate: At what scope I should use transaction?

后端 未结 1 366
暗喜
暗喜 2021-01-27 17:19

I am developing Data Access Layer using NHibernate. It will be used in my Business Logic Layer. My application is collection of multiple other applications (ASP.NET MVC, Windows

1条回答
  •  伪装坚强ぢ
    2021-01-27 18:05

    Why not make the service(s) transaction aware?

    something like

        protected virtual TResult Transact(Func func)
        {
            if (_session.Transaction.IsActive)
                return func.Invoke();
    
            TResult result;
            using (var tx = _session.BeginTransaction(IsolationLevel.ReadCommitted))
            {
                result = func.Invoke();
                tx.Commit();
            }
    
            return result;
        }
    
        protected virtual void Transact(System.Action action)
        {
            Transact(() =>
            {
                action.Invoke();
                return false;
            });
        }
    

    in your service or repo that checks if a transaction is active and participates in an active one or creates a new transaction if non exists.

    Now you can compose multiple service calls together under one transcation instead of having each call in isolation.

    0 讨论(0)
提交回复
热议问题