OperationBehaviorAttribute.TransactionScopeRequired Propiedad

Definición

Obtiene o establece un valor que indica si el método requiere un ámbito de la transacción para su ejecución.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

Valor de propiedad

true si el método exige que un ámbito de la transacción se ejecute; de lo contrario, false.true if the method requires a transaction scope to execute; otherwise, false. De manera predeterminada, es false.The default is false.

Ejemplos

El ejemplo de código siguiente muestra una operación que se ejecuta dentro de una transacción distribuida obligatoria.The following code example shows an operation that executes within a mandatory distributed transaction. La propiedad TransactionScopeRequired indica que la operación se ejecuta bajo un ámbito de la transacción, y la propiedad TransactionAutoComplete indica que, si no se produce ninguna excepción no controlada, se completa el ámbito de la transacción automáticamente.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. Si se produce una excepción no controlada, se anula la transacción.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

Comentarios

Establezca TransactionScopeRequired en true para exigir que su operación se ejecute dentro de un ámbito de la transacción.Set the TransactionScopeRequired to true to require your operation to execute within a transaction scope. Si una transacción de flujo está disponible, la operación se ejecuta dentro de esa transacción.If a flowed transaction is available, the operation executes within that transaction. Si ninguna está disponible, se crea una nueva transacción y se utiliza para la ejecución de la operación.If one is not available, a new transaction is created and used for the operation execution. El enlace especificado en el extremo controla si se admiten las transacciones de flujo.The binding specified in the endpoint controls whether flowed transactions are supported. Por consiguiente, para obtener el comportamiento apropiado debe entender la interacción entre si el enlace y la propiedad TransactionScopeRequired permiten el flujo de transacciones.Therefore, to obtain the proper behavior you must understand the interaction between whether transaction flow is permitted by the binding and the TransactionScopeRequired property. En la siguiente tabla se muestra el posible comportamiento.The following table shows the possible behavior.

TransactionScopeRequiredTransactionScopeRequired El enlace permite el flujo de transaccionesBinding permits transaction flow El autor de la llamada fluye la transacciónCaller flows transaction ResultadoResult
FalseFalse FalseFalse NoNo El método se ejecuta sin una transacción.Method executes without a transaction.
TrueTrue FalseFalse NoNo El método se crea y se ejecuta dentro de una nueva transacción.Method creates and executes within a new transaction.
True o FalseTrue or False FalseFalse Yes Se devuelve un error de SOAP para el encabezado de transacción.A SOAP fault is returned for the transaction header.
FalseFalse TrueTrue Yes El método se ejecuta sin una transacción.Method executes without a transaction.
TrueTrue TrueTrue Yes El método se ejecuta bajo la transacción fluida.Method executes under the flowed transaction.

Se aplica a