public interface ITransaction : IDisposable
    {
        bool IsActive { get; }
        bool WasCommitted { get; }
        bool WasRolledBack { get; }

        void Begin();
        void Begin(IsolationLevel isolationLevel);
        void Commit();
        void Enlist(IDbCommand command);
        void RegisterSynchronization(ISynchronization synchronization); //就是你了
        void Rollback();
    }

 

看到RegisterSynchronization(ISynchronization synchronization)这个方法了吗?这个方法就是给事务加入同步任务的。

 

public interface ISynchronization
    {
        void AfterCompletion(bool success);
        void BeforeCompletion();
    }

看到了吧?在完成之前,在完成之后,而且还带有一个事务是否成功。

 

于是,我们在Reposity里面注册这个,用2个Action即可实现完成后的Callback。

 

public virtual void MakePersistent(T entity, Action before, Action<bool> after)
        {
            Session.Transaction.RegisterSynchronization(new DefaultSynchronization(before, after));
            Session.SaveOrUpdate(entity);
        }
public class DefaultSynchronization : ISynchronization
    {
        private readonly Action _beforeCompletion;
        private readonly Action<bool> _afterCompletion;

        public DefaultSynchronization(Action<bool> after)
            : this(default(Action), after)
        { }

        public DefaultSynchronization(Action before, Action<bool> after)
        {
            _beforeCompletion = before;
            _afterCompletion = after;
        }

        public void AfterCompletion(bool success)
        {
            if (_afterCompletion != default(Action<bool>))
                _afterCompletion(success);
        }

        public void BeforeCompletion()
        {
            if (_beforeCompletion != default(Action))
                _beforeCompletion();
        }

如何使用?

这样:

MakePersistent(entity,()=>Console.Write("在事务之前执行”), isSuccess=>Console.Write(String.Format("在事务之后执行,结果:{0}", isSuccess)));

 

 

 

 

 

 

相关文章:

  • 2021-07-31
  • 2021-11-27
  • 2021-11-02
  • 2021-10-12
  • 2022-01-16
  • 2021-04-22
  • 2021-05-05
  • 2022-01-03
猜你喜欢
  • 2022-12-23
  • 2022-02-08
  • 2022-12-23
  • 2021-11-14
  • 2018-11-11
  • 2021-10-29
  • 2020-06-28
相关资源
相似解决方案