添加事务
有些方法可能需要事务支持,我们可能希望事务和业务分开的,也就是说当编写业务代码时根本就不用关心事务,下面我们看一个场景,一个银行帐
户管理类中有一个用于转账的方法,代码如下:
Code
class AccountManager
{
public void Trans(Account a1, Account a2,decimal money)
{
a1.Money = a1.Money - money;
a2.Money = a2.Money + money;
Update(a1.AccoutID, a1);
Update(a2.AccoutID, a2);
}
public void Update(int id,Account account)
{
using (DataClasses1DataContext dc=new DataClasses1DataContext())
{
var a = dc.Account.First(t => t.AccoutID == id);
a.Money = account.Money;
dc.SubmitChanges();
}
}
}
class AccountManager
{
public void Trans(Account a1, Account a2,decimal money)
{
a1.Money = a1.Money - money;
a2.Money = a2.Money + money;
Update(a1.AccoutID, a1);
Update(a2.AccoutID, a2);
}
public void Update(int id,Account account)
{
using (DataClasses1DataContext dc=new DataClasses1DataContext())
{
var a = dc.Account.First(t => t.AccoutID == id);
a.Money = account.Money;
dc.SubmitChanges();
}
}
}
现在我不想修改这部分代码但希望Trans方法是一个事务,下面我们使用PostSharp来实现:
首先引入PostSharp.Laos,PostSharp.Public两个程序集,另外还需引入System.Transactions程序集,添加TransactionScopeAttribte类:
Code
[Serializable]
class TransactionScopeAttribte : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
TransactionOptions transactionOptions = new TransactionOptions();
TransactionScopeOption transactionScopeOption = TransactionScopeOption.Required;
EnterpriseServicesInteropOption interopOption = EnterpriseServicesInteropOption.Automatic;
eventArgs.MethodExecutionTag = new TransactionScope(transactionScopeOption, transactionOptions, interopOption);
}
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
TransactionScope transactionScope = (TransactionScope)eventArgs.MethodExecutionTag;
if (eventArgs.Exception == null)
{
transactionScope.Complete();
transactionScope.Dispose();
}
else
{
transactionScope.Dispose();
}
}
}
[Serializable]
class TransactionScopeAttribte : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
TransactionOptions transactionOptions = new TransactionOptions();
TransactionScopeOption transactionScopeOption = TransactionScopeOption.Required;
EnterpriseServicesInteropOption interopOption = EnterpriseServicesInteropOption.Automatic;
eventArgs.MethodExecutionTag = new TransactionScope(transactionScopeOption, transactionOptions, interopOption);
}
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
TransactionScope transactionScope = (TransactionScope)eventArgs.MethodExecutionTag;
if (eventArgs.Exception == null)
{
transactionScope.Complete();
transactionScope.Dispose();
}
else
{
transactionScope.Dispose();
}
}
}
然后将属性标识在需要添加事务的方法上
[TransactionScopeAttribte]
public static void Trans(Account a1, Account a2,decimal money)
{
这样这个Trans方法就包括在事务中了。
注意:这里需要开启数据库所在机器的Distributed Transaction Coordinator服务。