OperationContext 클래스

정의

서비스 메서드의 실행 컨텍스트에 대한 액세스를 제공합니다.

public ref class OperationContext sealed : System::ServiceModel::IExtensibleObject<System::ServiceModel::OperationContext ^>
public sealed class OperationContext : System.ServiceModel.IExtensibleObject<System.ServiceModel.OperationContext>
type OperationContext = class
    interface IExtensibleObject<OperationContext>
Public NotInheritable Class OperationContext
Implements IExtensibleObject(Of OperationContext)
상속
OperationContext
구현

예제

다음 코드 예제에서는 Current 속성 및 GetCallbackChannel 메서드를 사용하여 메서드 내에서 호출자로 반환되는 채널을 가져옵니다. 이 예제의 모든 메서드는 단방향 메서드이므로 서비스와 클라이언트의 각 방향에서 독립적으로 통신할 수 있습니다. 이 경우 예제 클라이언트 애플리케이션은 종료되기 전에 하나의 반환 호출만 예상하지만 Windows Forms 클라이언트와 같은 다른 클라이언트는 서비스에서 여러 개의 호출을 받을 수 있습니다.

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(
    Name = "SampleDuplexHello",
    Namespace = "http://microsoft.wcf.documentation",
    CallbackContract = typeof(IHelloCallbackContract),
    SessionMode = SessionMode.Required
  )]
  public interface IDuplexHello
  {
    [OperationContract(IsOneWay = true)]
    void Hello(string greeting);
  }

  public interface IHelloCallbackContract
  {
    [OperationContract(IsOneWay = true)]
    void Reply(string responseToGreeting);
  }

  public class DuplexHello : IDuplexHello
  {
    public DuplexHello()
    {
      Console.WriteLine("Service object created: " + this.GetHashCode().ToString());
    }

    ~DuplexHello()
    {
      Console.WriteLine("Service object destroyed: " + this.GetHashCode().ToString());
    }

    public void Hello(string greeting)
    {
      Console.WriteLine("Caller sent: " + greeting);
      Console.WriteLine("Session ID: " + OperationContext.Current.SessionId);
      Console.WriteLine("Waiting two seconds before returning call.");
      // Put a slight delay to demonstrate asynchronous behavior on client.
      Thread.Sleep(2000);
      IHelloCallbackContract callerProxy
        = OperationContext.Current.GetCallbackChannel<IHelloCallbackContract>();
      string response = "Service object " + this.GetHashCode().ToString() + " received: " + greeting;
      Console.WriteLine("Sending back: " + response);
      callerProxy.Reply(response);
    }
  }
}


Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.Threading

Namespace Microsoft.WCF.Documentation
    <ServiceContract(Name:="SampleDuplexHello", Namespace:="http://microsoft.wcf.documentation", _
                     CallbackContract:=GetType(IHelloCallbackContract), SessionMode:=SessionMode.Required)> _
  Public Interface IDuplexHello
        <OperationContract(IsOneWay:=True)> _
        Sub Hello(ByVal greeting As String)
    End Interface

  Public Interface IHelloCallbackContract
    <OperationContract(IsOneWay := True)> _
    Sub Reply(ByVal responseToGreeting As String)
  End Interface

  Public Class DuplexHello
      Implements IDuplexHello
    Public Sub New()
      Console.WriteLine("Service object created: " & Me.GetHashCode().ToString())
    End Sub

    Protected Overrides Sub Finalize()
      Console.WriteLine("Service object destroyed: " & Me.GetHashCode().ToString())
    End Sub

    Public Sub Hello(ByVal greeting As String) Implements IDuplexHello.Hello
      Console.WriteLine("Caller sent: " & greeting)
      Console.WriteLine("Session ID: " & OperationContext.Current.SessionId)
      Console.WriteLine("Waiting two seconds before returning call.")
      ' Put a slight delay to demonstrate asynchronous behavior on client.
      Thread.Sleep(2000)
            Dim callerProxy = OperationContext.Current.GetCallbackChannel(Of IHelloCallbackContract)()
            Dim response = "Service object " & Me.GetHashCode().ToString() & " received: " & greeting
      Console.WriteLine("Sending back: " & response)
      callerProxy.Reply(response)
    End Sub
  End Class
End Namespace

다음 클라이언트는 SampleDuplexHelloCallback을 구현하여 콜백 메시지를 받습니다. 앞의 예제에서는 Name 속성을 사용하므로 가져온 콜백 계약의 이름이 서비스의 콜백 계약과 다릅니다. 클라이언트에서는 콜백 수신 여부 및 시기에 대해 어떠한 가정도 하지 않으므로 서버 콜백은 클라이언트 아웃바운드 호출로부터 완전히 독립적입니다.

참고

클라이언트 시나리오에서 OperationContext 클래스를 사용하는 예제의 경우 OperationContextScope를 참조하십시오.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;

namespace Microsoft.WCF.Documentation
{
  public class Client : SampleDuplexHelloCallback
  {
    AutoResetEvent waitHandle;

    public Client()
    {
      waitHandle = new AutoResetEvent(false);
    }

    public void Run()
    {
      // Picks up configuration from the config file.
      SampleDuplexHelloClient wcfClient
        = new SampleDuplexHelloClient(new InstanceContext(this));
      try
      {
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("Enter a greeting to send and press ENTER: ");
        Console.Write(">>> ");
        Console.ForegroundColor = ConsoleColor.Green;
        string greeting = Console.ReadLine();
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("Called service with: \r\n\t" + greeting);
        wcfClient.Hello(greeting);
        Console.WriteLine("Execution passes service call and moves to the WaitHandle.");
        this.waitHandle.WaitOne();
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine("Set was called.");
        Console.Write("Press ");
        Console.ForegroundColor = ConsoleColor.Red;
        Console.Write("ENTER");
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.Write(" to exit...");
        Console.ReadLine();
        wcfClient.Close();
      }
      catch (TimeoutException timeProblem)
      {
        Console.WriteLine("The service operation timed out. " + timeProblem.Message);
        Console.ReadLine();
        wcfClient.Abort();
      }
      catch (CommunicationException commProblem)
      {
        Console.WriteLine("There was a communication problem. " + commProblem.Message);
        Console.ReadLine();
        wcfClient.Abort();
      }
    }

    public static void Main()
    {
      Client client = new Client();
      client.Run();
    }

    public void Reply(string response)
    {
      Console.WriteLine("Received output.");
      Console.WriteLine("\r\n\t" + response);
      this.waitHandle.Set();
    }
  }
}

Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.Threading

Namespace Microsoft.WCF.Documentation
  Public Class Client
      Implements SampleDuplexHelloCallback
    Private waitHandle As AutoResetEvent

    Public Sub New()
      waitHandle = New AutoResetEvent(False)
    End Sub

    Public Sub Run()
      ' Picks up configuration from the config file.
      Dim wcfClient As New SampleDuplexHelloClient(New InstanceContext(Me))
      Try
        Console.ForegroundColor = ConsoleColor.White
        Console.WriteLine("Enter a greeting to send and press ENTER: ")
        Console.Write(">>> ")
        Console.ForegroundColor = ConsoleColor.Green
                Dim greeting = Console.ReadLine()
        Console.ForegroundColor = ConsoleColor.White
        Console.WriteLine("Called service with: " & Constants.vbCrLf & Constants.vbTab & greeting)
        wcfClient.Hello(greeting)
        Console.WriteLine("Execution passes service call and moves to the WaitHandle.")
        Me.waitHandle.WaitOne()
        Console.ForegroundColor = ConsoleColor.Blue
        Console.WriteLine("Set was called.")
        Console.Write("Press ")
        Console.ForegroundColor = ConsoleColor.Red
        Console.Write("ENTER")
        Console.ForegroundColor = ConsoleColor.Blue
        Console.Write(" to exit...")
        Console.ReadLine()
        wcfClient.Close()
      Catch timeProblem As TimeoutException
        Console.WriteLine("The service operation timed out. " & timeProblem.Message)
        Console.ReadLine()
        wcfClient.Abort()
      Catch commProblem As CommunicationException
        Console.WriteLine("There was a communication problem. " & commProblem.Message)
        Console.ReadLine()
        wcfClient.Abort()
      End Try
    End Sub

    Public Shared Sub Main()
      Dim client As New Client()
      client.Run()
    End Sub

    Public Sub Reply(ByVal response As String) Implements SampleDuplexHelloCallback.Reply
      Console.WriteLine("Received output.")
      Console.WriteLine(Constants.vbCrLf & Constants.vbTab & response)
      Me.waitHandle.Set()
    End Sub
  End Class
End Namespace

설명

현재 작업 실행 환경에 액세스하려면 서비스 작업에서 OperationContext를 사용합니다. 특히 작업 컨텍스트는 보내는 메시지 헤더와 속성을 추가하는 데 사용될 뿐만 아니라 이중 서비스에서 콜백 채널에 액세스하고, 작업 전체의 추가 상태 데이터를 저장하며, 들어오는 메시지 헤더와 속성에 액세스하는 데 사용됩니다.

확장을 사용 하 여 상태 데이터를 저장 하는 방법에 대 한 자세한 내용은 참조 하세요. 확장 가능한 개체합니다.

OperationContext에는 다음과 같은 속성 및 메서드가 있습니다.

생성자

OperationContext(IContextChannel)

클라이언트 애플리케이션에서 지정된 OperationContext을 사용하는 IContextChannel 클래스의 새 인스턴스를 초기화합니다.

속성

Channel

현재 OperationContext 개체와 연결된 채널을 가져옵니다.

ClaimsPrincipal

작업에 연결된 클레임 기반 보안 주체를 가져옵니다.

Current

현재 스레드의 실행 컨텍스트를 가져오거나 설정합니다.

EndpointDispatcher

검사하거나 수정할 엔드포인트의 엔드포인트 디스패처를 가져오거나 설정합니다.

Extensions

현재 메시지 컨텍스트에서 서비스 확장명의 컬렉션을 가져옵니다.

HasSupportingTokens

들어오는 메시지에서 토큰을 지원하는지 여부를 나타내는 값을 가져옵니다.

Host

현재 서비스 개체에 대한 ServiceHost를 가져옵니다.

IncomingMessageHeaders

OperationContext의 들어오는 메시지 헤더를 가져옵니다.

IncomingMessageProperties

OperationContext에서 들어오는 메시지의 메시지 속성을 가져옵니다.

IncomingMessageVersion

OperationContext의 들어오는 SOAP 메시지 버전을 가져옵니다.

InstanceContext

현재 서비스 인스턴스를 관리하는 InstanceContext 개체를 가져옵니다.

IsUserContext

이 속성은 시스템에서만 사용할 수 있으며 사용자는 호출할 수 없습니다.

OutgoingMessageHeaders

활성 OperationContext의 보내는 메시지 헤더를 가져옵니다.

OutgoingMessageProperties

활성 OperationContext에서 아웃바운드 메시지의 메시지 속성을 가져옵니다.

RequestContext

이 메서드에 대한 RequestContext 구현을 가져오거나 설정합니다.

ServiceSecurityContext

이 메서드를 실행할 ServiceSecurityContext를 가져오거나 설정합니다.

SessionId

현재 세션을 확인하는 데 사용되는 String을 가져옵니다.

SupportingTokens

ICollection<T> 형식의 SecurityToken을 가져옵니다.

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetCallbackChannel<T>()

현재 작업을 호출한 클라이언트 인스턴스로 채널을 가져옵니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
SetTransactionComplete()

현재 실행 중인 트랜잭션을 커밋합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

이벤트

OperationCompleted

작업이 완료되면 발생합니다.

적용 대상