WCF开发工具中对于事务的相关处理是一个比较重要的操作技术,我们在学习的过程中需要对此加强注意力。把事务放到客户端控制,实际上WCF控制事务还是在服务器端的,只不过操作权给了客户端而已。思路和WebService实现是一样的,即用WCF的状态化记住控制事务所需的对象,然后给客户端提供接口来操作这些对象。
闲话少说,WCF控制事务代码如下:
服务器端代码:
- [ServiceContract(SessionModeSessionMode=SessionMode.Required)]
- public interface IMyService{
- [OperationContract(IsTerminating=true)]
- void ReleaseSession();
- [OperationContract]
- void BeginTransaction();
- [OperationContract]
- void CommitTransaction();
- [OperationContract]
- void RollbackTransaction();
- [OperationContract]
- int ExecuteNonQuery(string strCmdText);}
- [ServiceBehavior(InstanceContextModeInstanceContextMode=
InstanceContextMode.PerSession)]- public class MyService : IMyService{private string strConnString =
"server=namihei2\\KHOS;database=AEGIS_TEST;- uid=sa;pwd=Password01!";
- private SqlConnection mySqlConnection;
- private SqlTransaction mySqlTransaction;
- public void ReleaseSession(){
- if (mySqlConnection.State == ConnectionState.Open)
{mySqlConnection.Close();- }}
- public void BeginTransaction(){
- mySqlConnection = new SqlConnection(strConnString);
- mySqlConnection.Open();
- mySqlTransaction = mySqlConnection.BeginTransaction();
- }
- public void CommitTransaction(){
- mySqlTransaction.Commit();
- }
- public void RollbackTransaction(){mySqlTransaction.Rollback();
- }
- public int ExecuteNonQuery(string strCmdText)
- {
- try{SqlCommand objSqlCommand = new SqlCommand(strCmdText);
- objSqlCommand.Connection = mySqlConnection;
- objSqlCommand.Transaction = mySqlTransaction;
- return objSqlCommand.ExecuteNonQuery();
- }
- catch (Exception ex){
- throw new FaultException(ex.Message);
- }}}
客户端代码:
- static void Main(string[] args){
- Console.WriteLine("Session Transaction Begin");
- SessionTrans.MyServiceClient serviceProxy =
new ConsoleTest.SessionTrans.MyServiceClient();- try{serviceProxy.BeginTransaction();
- serviceProxy.ExecuteNonQuery("update ATMAccount set Amount = 1000");
- serviceProxy.ExecuteNonQuery("insert into ATMLog
(AccountNumber,OperationType)- values ('888', 'good')");
- //serviceProxy.ExecuteNonQuery("insert into ATMLog
(AccountNumber,OperationType)- values ('888', 'goodgoodgoodgoodgoodgoodgoodgoodgoodgoodgoodgood
goodgoodgoodgoodgood')");- serviceProxy.CommitTransaction();
- }
- catch (Exception ex){Console.WriteLine(ex.Message);
- serviceProxy.RollbackTransaction();
- }
- finally{serviceProxy.ReleaseSession();
- serviceProxy.Close();
- }
- Console.WriteLine("Session Transaction End");
- Console.Read();
以上就是对WCF控制事务的相关介绍。
【编辑推荐】