ServiceBehaviorAttribute.InstanceContextMode ServiceBehaviorAttribute.InstanceContextMode ServiceBehaviorAttribute.InstanceContextMode ServiceBehaviorAttribute.InstanceContextMode Property

Définition

Obtient ou définit la valeur qui indique à quel moment de nouveaux objets de service sont créés.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

Valeur de propriété

Une des valeurs de InstanceContextMode ; la valeur par défaut est PerSession.One of the InstanceContextMode values; the default value is PerSession.

Exceptions

Exemples

L'exemple de code suivant illustre les propriétés ServiceBehaviorAttribute.The following code example demonstrates the ServiceBehaviorAttribute properties. La classe BehaviorService utilise l'attribut ServiceBehaviorAttribute pour indiquer que :The BehaviorService class uses the ServiceBehaviorAttribute attribute to indicate that:

  • Les méthodes d'implémentation sont appelées sur le thread d'interface utilisateur.Implementation methods are invoked on the UI thread.

  • Il existe un objet du service pour chaque session.There is one service object for each session.

  • Le service est monothread et ne prend pas en charge les appels réentrants.The service is single-threaded and does not support reentrant calls.

En outre, au niveau de l’opération, les valeurs OperationBehaviorAttribute indiquent que la méthode TxWork s’inscrit automatiquement dans les transactions passées ou crée une transaction pour faire le travail, et que la transaction est validée automatiquement si aucune exception non gérée ne se produit.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

La liaison sous-jacente doit prendre en charge les transactions passées pour l’exemple de code suivant pour s’exécuter correctement.The underlying binding must support flowed transactions for the following code example to execute properly. Pour prendre en charge les transactions passées à l’aide de WSHttpBinding, par exemple, affectez la valeur TransactionFlow à la propriété true dans le code ou dans un fichier de configuration de l’application.To support flowed transactions using the WSHttpBinding, for example, set the TransactionFlow property to true in code or in an application configuration file. L'exemple de code suivant montre le fichier de configuration pour l'exemple précédent :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>

Remarques

Utilisez la propriété InstanceContextMode pour spécifier à quel moment de nouveaux objets de service sont créés.Use the InstanceContextMode property to specify when new service objects are created. Comme l'objet de service n'est pas directement connecté au canal de communication, la durée de vie des objets de service est indépendante de la durée de vie du canal entre un client et l'application de service.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. La valeur par défaut, PerSession, demande à l'application de service de créer un objet du service lorsqu'une nouvelle session de communication est ouverte entre un client et l'application de service.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. Les appels ultérieurs au cours de cette session sont gérés par le même objet.Subsequent calls in the same session are handled by the same object.

PerSession indique que chaque objet de service gère les demandes d'un seul canal client.PerSession indicates that each service object handles requests from one client channel.

Notes

La propriété InstanceContextMode interagit avec plusieurs autres paramètres.The InstanceContextMode property interacts with some other settings. Par exemple, si InstanceContextMode a la valeur Single, votre service ne peut traiter qu'un message à la fois, excepté si vous affectez la valeur ConcurrencyMode à 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. Cette propriété produit également un comportement en association avec la propriété ServiceContractAttribute.SessionMode.This property also produces behavior in combination with the ServiceContractAttribute.SessionMode property. Pour plus d’informations, consultez sessions, instanciation et accès concurrentiel.For details, see Sessions, Instancing, and Concurrency.

Dans le cas du comportement de durée de vie singleton (par exemple, si l'application hôte appelle le constructeur ServiceHost et passe un objet à utiliser en tant que service), la classe de service doit affecter la valeur InstanceContextMode à Single. Sinon, une exception sera levée au moment de l'exécution.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.

S’applique à