小技巧:NHibernate做完一个操作(事务级别)如何Callback?
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)));