OperationContext OperationContext OperationContext OperationContext Class


Provides access to the execution context of a service method.

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)


The following code example uses the Current property and GetCallbackChannel method to obtain the channel back to the caller from within a method. All methods in this example are one-way methods, enabling the service and the client to communicate in both directions independently. In this case, the example client application expects only one return call before it exits, but another client, for example a Windows Forms client, can receive any number of calls from the service.

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

namespace Microsoft.WCF.Documentation
    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());

      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.
      IHelloCallbackContract callerProxy
        = OperationContext.Current.GetCallbackChannel<IHelloCallbackContract>();
      string response = "Service object " + this.GetHashCode().ToString() + " received: " + greeting;
      Console.WriteLine("Sending back: " + 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.
            Dim callerProxy = OperationContext.Current.GetCallbackChannel(Of IHelloCallbackContract)()
            Dim response = "Service object " & Me.GetHashCode().ToString() & " received: " & greeting
      Console.WriteLine("Sending back: " & response)
    End Sub
  End Class
End Namespace

The following client implements the SampleDuplexHelloCallback to receive the callback message. The imported callback contract is not the same name as the one in the service, due to the use of the Name property in the preceding example. Note that the client makes no assumptions about whether or when it might receive a callback; the server callback is entirely independent of the client's outbound call.


For an example that uses the OperationContext class in a client scenario, see 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));
        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);
        Console.WriteLine("Execution passes service call and moves to the WaitHandle.");
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine("Set was called.");
        Console.Write("Press ");
        Console.ForegroundColor = ConsoleColor.Red;
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.Write(" to exit...");
      catch (TimeoutException timeProblem)
        Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      catch (CommunicationException commProblem)
        Console.WriteLine("There was a communication problem. " + commProblem.Message);

    public static void Main()
      Client client = new Client();

    public void Reply(string response)
      Console.WriteLine("Received output.");
      Console.WriteLine("\r\n\t" + response);

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))
        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)
        Console.WriteLine("Execution passes service call and moves to the WaitHandle.")
        Console.ForegroundColor = ConsoleColor.Blue
        Console.WriteLine("Set was called.")
        Console.Write("Press ")
        Console.ForegroundColor = ConsoleColor.Red
        Console.ForegroundColor = ConsoleColor.Blue
        Console.Write(" to exit...")
      Catch timeProblem As TimeoutException
        Console.WriteLine("The service operation timed out. " & timeProblem.Message)
      Catch commProblem As CommunicationException
        Console.WriteLine("There was a communication problem. " & commProblem.Message)
      End Try
    End Sub

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

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


Use the OperationContext from within a service operation to access the current operation execution environment. In particular, the operation context is used to access callback channels in duplex services, to store extra state data across portions of the operations, and to access incoming message headers and properties as well as add outgoing message headers and properties.

For more information about using extensions to store state data, see Extensible Objects.

The OperationContext has the following properties and methods.


OperationContext(IContextChannel) OperationContext(IContextChannel) OperationContext(IContextChannel) OperationContext(IContextChannel)

Initializes a new instance of the OperationContext class that uses the specified IContextChannel in a client application.


Channel Channel Channel Channel

Gets the channel associated with the current OperationContext object.

ClaimsPrincipal ClaimsPrincipal ClaimsPrincipal ClaimsPrincipal

Gets the claims-based principal associated with the operation.

Current Current Current Current

Gets or sets the execution context for the current thread.

EndpointDispatcher EndpointDispatcher EndpointDispatcher EndpointDispatcher

Gets or sets the endpoint dispatcher for the endpoint to inspect or modify.

Extensions Extensions Extensions Extensions

Gets the collection of service extensions from the current message context.

HasSupportingTokens HasSupportingTokens HasSupportingTokens HasSupportingTokens

Gets a value that indicates whether the incoming message has supporting tokens.

Host Host Host Host

Gets the ServiceHost for the current service object.

IncomingMessageHeaders IncomingMessageHeaders IncomingMessageHeaders IncomingMessageHeaders

Gets the incoming message headers for the OperationContext.

IncomingMessageProperties IncomingMessageProperties IncomingMessageProperties IncomingMessageProperties

Gets the message properties for the incoming message in the OperationContext.

IncomingMessageVersion IncomingMessageVersion IncomingMessageVersion IncomingMessageVersion

Gets the incoming SOAP message version for the OperationContext.

InstanceContext InstanceContext InstanceContext InstanceContext

Gets the InstanceContext object that manages the current service instance.

IsUserContext IsUserContext IsUserContext IsUserContext

This property is intended for system use and should not be called by users.

OutgoingMessageHeaders OutgoingMessageHeaders OutgoingMessageHeaders OutgoingMessageHeaders

Gets the outgoing message headers for the active OperationContext.

OutgoingMessageProperties OutgoingMessageProperties OutgoingMessageProperties OutgoingMessageProperties

Gets the message properties for the outbound message in the active OperationContext.

RequestContext RequestContext RequestContext RequestContext

Gets or sets the RequestContext implementation for this method.

ServiceSecurityContext ServiceSecurityContext ServiceSecurityContext ServiceSecurityContext

Gets or sets the ServiceSecurityContext within which this method executes.

SessionId SessionId SessionId SessionId

Gets the String used to identify the current session.

SupportingTokens SupportingTokens SupportingTokens SupportingTokens

Gets a ICollection<T> of type SecurityToken.


Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetCallbackChannel<T>() GetCallbackChannel<T>() GetCallbackChannel<T>() GetCallbackChannel<T>()

Gets a channel to the client instance that called the current operation.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
SetTransactionComplete() SetTransactionComplete() SetTransactionComplete() SetTransactionComplete()

Commits the currently executing transaction.

ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)


OperationCompleted OperationCompleted OperationCompleted OperationCompleted

Occurs when the operation has completed.

Applies to