ServiceBehaviorAttribute.InstanceContextMode Proprietà

Definizione

Ottiene o imposta il valore che indica quando vengono creati nuovi oggetti servizio.Gets or sets the value that indicates when new service objects are created.

public:
 property System::ServiceModel::InstanceContextMode InstanceContextMode { System::ServiceModel::InstanceContextMode get(); void set(System::ServiceModel::InstanceContextMode value); };
public System.ServiceModel.InstanceContextMode InstanceContextMode { get; set; }
member this.InstanceContextMode : System.ServiceModel.InstanceContextMode with get, set
Public Property InstanceContextMode As InstanceContextMode

Valore della proprietà

Uno dei valori dell'enumerazione InstanceContextMode; il valore predefinito è PerSession.One of the InstanceContextMode values; the default value is PerSession.

Eccezioni

Il valore non appartiene all'enumerazione InstanceContextMode.The value is not one of the InstanceContextMode values.

Esempi

Nell'esempio di codice seguente vengono illustrate le proprietà della classe ServiceBehaviorAttribute.The following code example demonstrates the ServiceBehaviorAttribute properties. La classe BehaviorService utilizza l'attributo ServiceBehaviorAttribute per indicare quanto segue:The BehaviorService class uses the ServiceBehaviorAttribute attribute to indicate that:

  • I metodi di implementazione sono richiamati sul thread UI.Implementation methods are invoked on the UI thread.

  • È presente un solo oggetto servizio per ogni sessione.There is one service object for each session.

  • Il servizio è a thread singolo e non supporta le chiamate rientranti.The service is single-threaded and does not support reentrant calls.

Inoltre, a livello di operazione, i valori della classe OperationBehaviorAttribute indicano che il metodo TxWork viene inserito automaticamente nelle transazioni propagate o crea una nuova transazione per l'esecuzione dell'operazione e che, se non si verifica alcuna eccezione non gestita, viene eseguito automaticamente il commit della transazione.Furthermore, at the operation level, the OperationBehaviorAttribute values indicate that the TxWork method automatically enlists in flowed transactions or creates a new transaction to do the work, and that the transaction is committed automatically if an unhandled exception does not occur.

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:
     *   -- The executing transaction is committed when
     *        the operation completes without an 
     *        unhandled exception
     *   -- Always executes under a flowed transaction.
     */
    [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:
        '     *   -- The executing transaction is committed when
        '     *        the operation completes without an 
        '     *        unhandled exception
        '     *   -- Always executes under a flowed transaction.
        '     
        <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

Affinché l'esempio di codice seguente venga eseguito correttamente, è necessario che l'associazione sottostante supporti le transazioni propagate.The underlying binding must support flowed transactions for the following code example to execute properly. Per supportare le transazioni propagate utilizzando l'associazione WSHttpBinding, ad esempio, impostare la proprietà TransactionFlow su true nel codice o in un file di configurazione dell'applicazione.To support flowed transactions using the WSHttpBinding, for example, set the TransactionFlow property to true in code or in an application configuration file. Nell'esempio di codice seguente viene illustrato il file di configurazione per l'esempio precedente.The following code example shows the configuration file for the preceding sample.

<configuration>
  <system.serviceModel>
    <services>
      <service  
        name="Microsoft.WCF.Documentation.BehaviorService" 
        behaviorConfiguration="metadataAndDebugEnabled"
      >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <!--
          Note:
            This example code uses the WSHttpBinding to support transactions using the 
            WS-AtomicTransactions (WS-AT) protocol. WSHttpBinding is configured to use the  
            protocol, but the protocol is not enabled on some computers. Use the xws_reg -wsat+ 
            command to enable the WS-AtomicTransactions protocol in the MSDTC service.          
          -->
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="wsHttpBinding"
           bindingConfiguration="wsHttpBindingWithTXFlow"
           address="http://localhost:8080/BehaviorService"
          />
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="netTcpBinding"
           bindingConfiguration="netTcpBindingWithTXFlow"
           address="net.tcp://localhost:8081/BehaviorService"
          />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
        />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataAndDebugEnabled">
          <serviceDebug
            includeExceptionDetailInFaults="true"
          />
          <serviceMetadata
            httpGetEnabled="true"
            httpGetUrl=""
          />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- binding configuration - configures a WSHttpBinding to require transaction flow -->
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpBindingWithTXFlow" transactionFlow="true" />
      </wsHttpBinding>
      <netTcpBinding>
        <binding name="netTcpBindingWithTXFlow" transactionFlow="true" />
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

Commenti

Utilizzare la proprietà InstanceContextMode per specificare quando vengono creati nuovi oggetti servizio.Use the InstanceContextMode property to specify when new service objects are created. Poiché l'oggetto servizio non è connesso direttamente al canale di comunicazione, la durata degli oggetti servizio è indipendente dalla durata del canale tra un client e l'applicazione del servizio.Because the service object is not directly connected to the communicating channel, the lifetime of the service objects is independent of the lifetime of the channel between a client and the service application. Il valore predefinito, PerSession, indica all'applicazione del servizio di creare un nuovo oggetto servizio quando viene stabilita una nuova sessione di comunicazione tra un client e l'applicazione del servizio.The default value, PerSession, instructs the service application to create a new service object when a new communication session is established between a client and the service application. Le chiamate successive all'interno della stessa sessione vengono gestite dallo stesso oggetto.Subsequent calls in the same session are handled by the same object.

PerSession indica che ogni oggetto servizio gestisce le richieste da un solo canale client.PerSession indicates that each service object handles requests from one client channel.

Nota

La proprietà InstanceContextMode interagisce con altre impostazioni.The InstanceContextMode property interacts with some other settings. Ad esempio, se si imposta il valore InstanceContextMode su Single, il servizio può elaborare un solo messaggio alla volta, a meno che il valore di ConcurrencyMode non venga impostato su Multiple.For example, if the InstanceContextMode value is set to Single the result is that your service can only process one message at a time unless you also set the ConcurrencyMode value to Multiple. Questa proprietà genera inoltre un comportamento in combinazione con la proprietà ServiceContractAttribute.SessionMode.This property also produces behavior in combination with the ServiceContractAttribute.SessionMode property. Per informazioni dettagliate, vedere sessioni, istanze e concorrenza.For details, see Sessions, Instancing, and Concurrency.

In caso di funzionamento di durata Singleton (ad esempio, l'applicazione host chiama il costruttore ServiceHost e passa un oggetto da utilizzare come servizio), la classe del servizio deve impostare la proprietà InstanceContextMode su Single. In caso contrario viene generata un'eccezione in fase di esecuzione.For singleton lifetime behavior (for example, if the host application calls the ServiceHost constructor and passes an object to use as the service), the service class must set InstanceContextMode to Single, or an exception is thrown at run time.

Si applica a