ServiceBehaviorAttribute.InstanceContextMode 속성

정의

새 서비스 개체 생성 시점을 나타내는 값을 가져오거나 설정합니다.

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

속성 값

InstanceContextMode

InstanceContextMode 값 중 하나입니다. 기본값은 PerSession입니다.

예외

값이 InstanceContextMode 값 중 하나가 아닌 경우

예제

다음 코드 예제에서는 ServiceBehaviorAttribute 속성을 보여 줍니다. BehaviorService 클래스는 ServiceBehaviorAttribute 특성을 사용하여 다음을 나타냅니다.

  • 구현 메서드가 UI 스레드에서 호출됩니다.

  • 세션별로 서비스 개체가 하나씩 있습니다.

  • 서비스는 단일 스레드이며 재진입 호출을 지원하지 않습니다.

또한 작업 수준에서 OperationBehaviorAttribute 값은 TxWork 메서드가 흐름이 지정된 트랜잭션에 자동으로 참여하거나 작업 수행을 위해 새로운 트랜잭션을 생성함을 나타내며 처리되지 않은 예외가 발생하지 않으면 트랜잭션이 자동으로 커밋됨을 나타냅니다.

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

다음 코드 예제가 제대로 실행되려면 기본 바인딩에서 트랜잭션 이동을 지원해야 합니다. 예를 들어, WSHttpBinding을 사용하여 트랜잭션 이동을 지원하려면 코드 또는 애플리케이션 구성 파일에서 TransactionFlow 속성을 true로 설정합니다. 다음 코드 예제에서는 앞에 나온 샘플에 대한 구성 파일을 보여 줍니다.

<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>

설명

새 서비스 개체 생성 시점을 지정하려면 InstanceContextMode 속성을 사용합니다. 서비스 개체가 통신 채널과 직접 연결되지 않으므로 서비스 개체의 수명은 클라이언트와 서비스 애플리케이션 사이의 채널이 가지는 수명과 관계가 없습니다. 기본값인 PerSession은 클라이언트와 서비스 애플리케이션 간에 새 통신 세션이 설정될 경우 서비스 애플리케이션이 새 서비스 개체를 만들도록 합니다. 동일 세션 내의 후속 호출은 동일한 개체가 처리합니다.

PerSession은 각 서비스 개체가 하나의 클라이언트 채널의 요청을 처리함을 나타냅니다.

참고

InstanceContextMode 속성은 다른 설정과 상호 작용합니다. 예를 들어, InstanceContextMode 값을 Single로 설정한 경우 ConcurrencyMode 값을 Multiple로 설정하지 않으면 서비스에서 한 번에 하나의 메시지만 처리할 수 있습니다. 또한 이 속성은 ServiceContractAttribute.SessionMode 속성과 함께 동작을 생성합니다. 자세한 내용은 참조 하세요 세션, Instancing, and Concurrency합니다.

단일 수명 동작(예: 호스트 애플리케이션이 ServiceHost 생성자를 호출하고 서비스로 사용할 개체를 전달하는 경우)에 대해서는 서비스 클래스에서 InstanceContextModeSingle로 설정해야 합니다. 그렇지 않으면 런타임에 예외가 throw됩니다.

적용 대상