OperationBehaviorAttribute.TransactionScopeRequired Proprietà

Definizione

Ottiene o imposta un valore che indica se per l'esecuzione del metodo è necessario un ambito di transazione.Gets or sets a value that indicates whether the method requires a transaction scope for its execution.

public:
 property bool TransactionScopeRequired { bool get(); void set(bool value); };
public bool TransactionScopeRequired { get; set; }
member this.TransactionScopeRequired : bool with get, set
Public Property TransactionScopeRequired As Boolean

Valore della proprietà

true se per l'esecuzione del metodo è necessario un ambito di transazione; in caso contrario, false.true if the method requires a transaction scope to execute; otherwise, false. Il valore predefinito è false.The default is false.

Esempi

Nell'esempio di codice seguente viene illustrata un'operazione eseguita all'interno di una transazione distribuita obbligatoria.The following code example shows an operation that executes within a mandatory distributed transaction. La proprietà TransactionScopeRequired indica che l'operazione viene eseguita nell'ambito di transazione, mentre la proprietà TransactionAutoComplete indica che, se non si verificano eccezioni non gestite, l'ambito di transazione viene completato automaticamente.The TransactionScopeRequired property indicates that the operation executes under a transaction scope and the TransactionAutoComplete property indicates that if no unhandled exceptions occur, the transaction scope is completed automatically. Se si verifica un'eccezione non gestita, la transazione viene interrotta.If an unhandled exception does occur, the transaction is aborted.

using System;
using System.ServiceModel;
using System.Transactions;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(Namespace="http://microsoft.wcf.documentation", SessionMode=SessionMode.Required)]
  public interface IBehaviorService
  {
    [OperationContract]
    string TxWork(string message);
  }

  // Note: To use the TransactionIsolationLevel property, you 
  // must add a reference to the System.Transactions.dll assembly.
  /* The following service implementation:
   *   -- Processes messages on one thread at a time
   *   -- Creates one service object per session
   *   -- Releases the service object when the transaction commits
   */
  [ServiceBehavior(
    ConcurrencyMode=ConcurrencyMode.Single,
    InstanceContextMode=InstanceContextMode.PerSession,
    ReleaseServiceInstanceOnTransactionComplete=true
  )]
  public class BehaviorService : IBehaviorService, IDisposable
  {
    Guid myID;

    public BehaviorService()
    {
      myID = Guid.NewGuid();
      Console.WriteLine(
        "Object "
        + myID.ToString()
        + " created.");
    }

    /*
     * The following operation-level behaviors are specified:
     *   -- Always executes under a transaction scope.
     *   -- The transaction scope is completed when the operation terminates 
     *       without an unhandled exception.
     */
    [OperationBehavior(
      TransactionAutoComplete = true,
      TransactionScopeRequired = true
    )]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public string TxWork(string message)
    {
      // Do some transactable work.
      Console.WriteLine("TxWork called with: " + message);
      // Display transaction information.

      TransactionInformation info = Transaction.Current.TransactionInformation;
      Console.WriteLine("The distributed tx ID: {0}.", info.DistributedIdentifier);
      Console.WriteLine("The tx status: {0}.", info.Status);
      return String.Format("Hello. This was object {0}.",myID.ToString()) ;
    }

    public void Dispose()
    {
      Console.WriteLine(
        "Service "
        + myID.ToString()
        + " is being recycled."
      );
    }
  }
}
Imports System.ServiceModel
Imports System.Transactions

Namespace Microsoft.WCF.Documentation
  <ServiceContract(Namespace:="http://microsoft.wcf.documentation", SessionMode:=SessionMode.Required)> _
  Public Interface IBehaviorService
    <OperationContract> _
    Function TxWork(ByVal message As String) As String
  End Interface

    ' Note: To use the TransactionIsolationLevel property, you 
    ' must add a reference to the System.Transactions.dll assembly.
    ' The following service implementation:
    '   *   -- Processes messages on one thread at a time
    '   *   -- Creates one service object per session
    '   *   -- Releases the service object when the transaction commits

    <ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Single, InstanceContextMode:=InstanceContextMode.PerSession, _
                     ReleaseServiceInstanceOnTransactionComplete:=True)> _
    Public Class BehaviorService
        Implements IBehaviorService, IDisposable
        Private myID As Guid

        Public Sub New()
            myID = Guid.NewGuid()
            Console.WriteLine("Object " & myID.ToString() & " created.")
        End Sub

        '    
        '     * The following operation-level behaviors are specified:
        '     *   -- Always executes under a transaction scope.
        '     *   -- The transaction scope is completed when the operation terminates 
        '     *       without an unhandled exception.
        '     
        <OperationBehavior(TransactionAutoComplete:=True, TransactionScopeRequired:=True), _
        TransactionFlow(TransactionFlowOption.Mandatory)> _
        Public Function TxWork(ByVal message As String) As String Implements IBehaviorService.TxWork
            ' Do some transactable work.
            Console.WriteLine("TxWork called with: " & message)
            ' Display transaction information.

            Dim info As TransactionInformation = Transaction.Current.TransactionInformation
            Console.WriteLine("The distributed tx ID: {0}.", info.DistributedIdentifier)
            Console.WriteLine("The tx status: {0}.", info.Status)
            Return String.Format("Hello. This was object {0}.", myID.ToString())
        End Function

        Public Sub Dispose() Implements IDisposable.Dispose
            Console.WriteLine("Service " & myID.ToString() & " is being recycled.")
        End Sub
    End Class
End Namespace

Commenti

Impostare la proprietà TransactionScopeRequired su true per richiedere che l'operazione sia eseguita all'interno di un ambito di transazione.Set the TransactionScopeRequired to true to require your operation to execute within a transaction scope. Se è disponibile una transazione propagata, l'operazione viene eseguita all'interno di tale transazione.If a flowed transaction is available, the operation executes within that transaction. In caso contrario, per l'esecuzione dell'operazione viene creata e utilizzata una nuova transazione.If one is not available, a new transaction is created and used for the operation execution. L'associazione specificata nell'endpoint controlla se sono supportate le transazioni propagate.The binding specified in the endpoint controls whether flowed transactions are supported. Per ottenere il comportamento corretto, è pertanto necessario comprendere l'interazione tra la propagazione transazionale eventualmente consentita dall'associazione e la proprietà TransactionScopeRequired.Therefore, to obtain the proper behavior you must understand the interaction between whether transaction flow is permitted by the binding and the TransactionScopeRequired property. Nella tabella seguente vengono illustrati i possibili comportamenti.The following table shows the possible behavior.

TransactionScopeRequiredTransactionScopeRequired L'associazione consente la propagazione transazionaleBinding permits transaction flow Il chiamante propaga la transazioneCaller flows transaction RisultatoResult
FalseFalse FalseFalse NoNo Il metodo viene eseguito senza una transazione.Method executes without a transaction.
TrueTrue FalseFalse NoNo Il metodo crea e viene eseguito all'interno di una nuova transazione.Method creates and executes within a new transaction.
True o false.True or False FalseFalse Yes Viene restituito un errore SOAP per l'intestazione della transazione.A SOAP fault is returned for the transaction header.
FalseFalse TrueTrue Yes Il metodo viene eseguito senza una transazione.Method executes without a transaction.
TrueTrue TrueTrue Yes Il metodo viene eseguito nella transazione propagata.Method executes under the flowed transaction.

Si applica a