OperationContextScope Klasa

Definicja

Tworzy blok, w którym OperationContext obiekt znajduje się w zakresie.

public ref class OperationContextScope sealed : IDisposable
public sealed class OperationContextScope : IDisposable
type OperationContextScope = class
    interface IDisposable
Public NotInheritable Class OperationContextScope
Implements IDisposable
Dziedziczenie
OperationContextScope
Implementuje

Przykłady

W poniższym przykładzie pokazano, jak utworzyć OperationContextScope nowy kontekst w aplikacji klienckiej w celu dodania niestandardowego nagłówka do komunikatu wychodzącego.

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

public class Client : ISampleServiceCallback
{
  ManualResetEvent wait = null;

  Client()
  {
    this.wait = new ManualResetEvent(false);
  }

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

  void Run()
  {
    // Picks up configuration from the config file.
    SampleServiceClient wcfClient = new SampleServiceClient(new InstanceContext(this));
    try
    {
      using (OperationContextScope scope = new OperationContextScope(wcfClient.InnerChannel))
      {
        MessageHeader header
          = MessageHeader.CreateHeader(
          "Service-Bound-CustomHeader",
          "http://Microsoft.WCF.Documentation",
          "Custom Happy Value."
          );
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        // Making calls.
        Console.WriteLine("Enter the greeting to send: ");
        string greeting = Console.ReadLine();

        //Console.ReadLine();
        header = MessageHeader.CreateHeader(
            "Service-Bound-OneWayHeader",
            "http://Microsoft.WCF.Documentation",
            "Different Happy Value."
          );
        OperationContext.Current.OutgoingMessageHeaders.Add(header);

        // One-way
        wcfClient.Push(greeting);
        this.wait.WaitOne();

        // Done with service.
        wcfClient.Close();
        Console.WriteLine("Done!");
        Console.ReadLine();
      }
    }
    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();
    }
  }


  #region ISampleServiceCallback Members

  public void PushBack(string msg)
  {
    Console.WriteLine("Service said: " + msg);
    this.WriteHeaders(OperationContext.Current.IncomingMessageHeaders);
    this.wait.Set();
  }

  void WriteHeaders(MessageHeaders headers)
  {
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("IncomingHeader:");
    Console.ForegroundColor = ConsoleColor.Blue;
    foreach (MessageHeaderInfo h in headers)
    {
      if (!h.Actor.Equals(String.Empty))
        Console.WriteLine("\t" + h.Actor);
      Console.ForegroundColor = ConsoleColor.White;
      Console.WriteLine("\t" + h.Name);
      Console.ForegroundColor = ConsoleColor.Blue;
      Console.WriteLine("\t" + h.Namespace);
      Console.WriteLine("\t" + h.Relay);
      if (h.IsReferenceParameter == true)
      {
        Console.WriteLine("IsReferenceParameter header detected: " + h.ToString());
      }
    }
    Console.ResetColor();
  }
  #endregion
}
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.Threading

Public Class Client
    Implements ISampleServiceCallback
  Private wait As ManualResetEvent = Nothing

  Private Sub New()
    Me.wait = New ManualResetEvent(False)
  End Sub

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

  Private Sub Run()
    ' Picks up configuration from the config file.
    Dim wcfClient As New SampleServiceClient(New InstanceContext(Me))
    Try
      Using scope As New OperationContextScope(wcfClient.InnerChannel)
                Dim header As MessageHeader = MessageHeader.CreateHeader("Service-Bound-CustomHeader", _
                                    "http://Microsoft.WCF.Documentation", "Custom Happy Value.")
        OperationContext.Current.OutgoingMessageHeaders.Add(header)

        ' Making calls.
        Console.WriteLine("Enter the greeting to send: ")
        Dim greeting As String = Console.ReadLine()

        'Console.ReadLine();
                header = MessageHeader.CreateHeader("Service-Bound-OneWayHeader", _
                                                    "http://Microsoft.WCF.Documentation", "Different Happy Value.")
        OperationContext.Current.OutgoingMessageHeaders.Add(header)

        ' One-way
        wcfClient.Push(greeting)
        Me.wait.WaitOne()

        ' Done with service. 
        wcfClient.Close()
        Console.WriteLine("Done!")
        Console.ReadLine()
      End Using
    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


  #Region "ISampleServiceCallback Members"

  Public Sub PushBack(ByVal msg As String) Implements ISampleServiceCallback.PushBack
    Console.WriteLine("Service said: " & msg)
    Me.WriteHeaders(OperationContext.Current.IncomingMessageHeaders)
    Me.wait.Set()
  End Sub

  Private Sub WriteHeaders(ByVal headers As MessageHeaders)
    Console.ForegroundColor = ConsoleColor.Red
    Console.WriteLine("IncomingHeader:")
    Console.ForegroundColor = ConsoleColor.Blue
    For Each h As MessageHeaderInfo In headers
      If Not h.Actor.Equals(String.Empty) Then
        Console.WriteLine(vbTab & h.Actor)
      End If
      Console.ForegroundColor = ConsoleColor.White
      Console.WriteLine(vbTab & h.Name)
      Console.ForegroundColor = ConsoleColor.Blue
      Console.WriteLine(vbTab & h.Namespace)
      Console.WriteLine(vbTab & h.Relay)
      If h.IsReferenceParameter = True Then
        Console.WriteLine("IsReferenceParameter header detected: " & h.ToString())
      End If
    Next h
    Console.ResetColor()
  End Sub
  #End Region

End Class

Uwagi

OperationContextScope Użyj klasy , aby utworzyć zakres dla określonego OperationContext obiektu lub zakresu dla nowego OperationContext obiektu przy użyciu określonego IContextChannel obiektu. Można OperationContextScope go używać w usłudze Windows Communication Foundation (WCF) lub aplikacji klienckiej WCF.

Po ustanowieniu OperationContextScope bieżącego kontekstu operacji można użyć polecenia OperationContext , aby:

  • Uzyskiwanie dostępu i modyfikowanie nagłówków przychodzących i wychodzących wiadomości oraz innych właściwości.

  • Uzyskaj dostęp do środowiska uruchomieniowego, w tym dyspozytorów, hosta, kanału i rozszerzeń.

  • Dostęp do innych typów kontekstów, takich jak zabezpieczenia, wystąpienie i konteksty żądań.

  • Uzyskaj dostęp do kanału skojarzonego z obiektem OperationContext lub (jeśli kanał implementuje System.ServiceModel.Channels.ISession) identyfikator sesji skojarzonego kanału.

Po utworzeniu OperationContextScope elementu bieżący OperationContext jest przechowywany, a nowy OperationContext staje się tym, który jest zwracany przez Current właściwość . Gdy element OperationContextScope zostanie usunięty, oryginalny OperationContext element zostanie przywrócony.

Ostrzeżenie

Nie używaj asynchronicznego wzorca "await" w bloku OperationContextScope. Gdy następuje kontynuacja, może działać w innym wątku, a element OperationContextScope jest specyficzny dla wątku. Jeśli musisz wywołać metodę "await" dla wywołania asynchronicznego, użyj go poza blokiem OperationContextScope.

Konstruktory

OperationContextScope(IContextChannel)

Inicjuje OperationContextScope nowe wystąpienie klasy, która używa określonego IContextChannel elementu do utworzenia nowego OperationContext dla zakresu.

OperationContextScope(OperationContext)

Inicjuje OperationContextScope nowe wystąpienie klasy w celu utworzenia zakresu dla określonego OperationContext obiektu.

Metody

Dispose()

Przywraca oryginalny OperationContext kontekst do aktywnego kontekstu i przetwarza OperationContextScope obiekt.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Dotyczy