web 在Web Service中實現Transaction
.Net Framework為類,WebForm和WebService提供了交易處理功能。
在傳統的windows應用程式中,要寫一個有交易處理功能的組件不僅要寫代碼而且要在元件服務中建立一個事務包。這就意味著在任何一台要處理這個事務的機器上,你都不得不開啟mmc在COM+應用程式節點下建立一個新包。
.NET Framework使得這一切變得很簡單,事實上我們不用在元件服務中作任何事,這一切都是自動完成的。對WebService來說,.NET Framework用Enterprise Services(COM+的替代者)來管理事務,而無需建立一個COM+包。所有管理事務狀態的工作都是在幕後完成的。
在webservice中實現這個很簡單。
1)在 [WebMethod()]屬性中指定transaction的類型。如[ WebMethod ( false, TransactionOption.RequiresNew) ]
以下是TransactionOption的詳細列表。
TransactionOption.Disabled Ignore any transaction in the current context.
TransactionOption.NotSupported Create the component in a context with no governing transaction.
TransactionOption.Supported Share a transaction if one exists; create a new transaction if necessary.
TransactionOption.Required Create the component with a new transaction, regardless of the state of the current context.
TransactionOption.RequiresNew Share a transaction if one exists.
2)用[AutoComplete]屬性確保Transaction能完成,除非拋出異常。
由此我們可以看出在Web Service中實現Transaction的一點特殊性,即Transaction屬性是應用於WebMethod上的。這意味著在webservice中只有設定了TransactionOption後才會應用事務。
注意:我們可以不要[AutoComplete],自己寫程式碼完成事務或中止事務,例子如下
try
{
//Update the balances:
//If an Account.Balance goes below 0,
//an exception is thrown by the Account object
_credit.Balance = _actDB.getBalance ( _credit.ID );
_debit.Balance = _actDB.getBalance ( _debit.ID );
ContextUtil.SetCommit;
}
//Catch the exception from the Account object
catch ( Exception ex )
{
ContextUtil.SetAbort;
}
附上我的一段代碼:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.EnterpriseServices;
namespace Michael.WebServiceTrans
{
public class FinancialUtil : System.Web.Services.WebService
{
//Create a class-level instance of the AccountDB class
Michael.Data.AccountDB _actDB = new Michael.Data.AccountDB();
//Return the new balances in the array
_array[0] = _debit.Balance;
_array[1] = _credit.Balance;
return _array;
}
[WebMethod()]
public DataSet GetAllAccountNumbers ()
{
return _actDB.getAllAccountNums();
}
//******************************************************//
//*********** VISUAL STUDIO DESIGNER CODE **************//
//******************************************************//
public FinancialUtil()
{
InitializeComponent();
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion