OperationContextScope Classe

Definizione

Consente di creare un blocco che definisce l'ambito di un oggetto OperationContext.Creates a block within which an OperationContext object is in scope.

public ref class OperationContextScope sealed : IDisposable
public sealed class OperationContextScope : IDisposable
type OperationContextScope = class
    interface IDisposable
Public NotInheritable Class OperationContextScope
Implements IDisposable
Ereditarietà
OperationContextScope
Implementazioni

Esempi

Nell'esempio seguente viene illustrato come utilizzare l'ambito OperationContextScope per creare un nuovo contesto in un'applicazione client per aggiungere un'intestazione personalizzata al messaggio in uscita.The following example shows how to use the OperationContextScope to create a new context in a client application to add a custom header to the outgoing message.

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

Commenti

Utilizzare la classe OperationContextScope per creare l'ambito di un oggetto OperationContext specifico o l'ambito di un nuovo oggetto OperationContext tramite l'oggetto IContextChannel specificato.Use the OperationContextScope class to create a scope for a specific OperationContext object or a scope for a new OperationContext object using a specified IContextChannel object. È possibile utilizzare un OperationContextScope in un servizio di Windows Communication Foundation (WCF) o in un'applicazione client WCF.An OperationContextScope can be used in a Windows Communication Foundation (WCF) service or WCF client application.

Dopo che l'oggetto OperationContextScope ha stabilito il contesto dell'operazione corrente, il contesto OperationContext può essere utilizzato per:Once the OperationContextScope object has established the current operation context, you can use the OperationContext to:

  • Accedere e modificare le intestazioni e le altre proprietà dei messaggi in ingresso e in uscita.Access and modify incoming and outgoing message headers and other properties.

  • Accedere al runtime, compresi dispatcher, host, canale ed estensioni.Access the runtime, including dispatchers, the host, channel, and extensions.

  • Accedere agli altri tipi di contesto, ad esempio ai contesti di sicurezza, istanza e richiesta.Access other types of contexts, such as security, instance, and request contexts.

  • Accedere al canale associato all'oggetto OperationContext o, se il canale implementa l'interfaccia System.ServiceModel.Channels.ISession, all'identificatore di sessione del canale associato.Access the channel associated with the OperationContext object or (if the channel implements System.ServiceModel.Channels.ISession) the associated channel's session identifier.

Quando si crea un ambito OperationContextScope, il contesto OperationContext corrente viene archiviato e il nuovo contesto OperationContext diventa quello restituito dalla proprietà Current.When an OperationContextScope is created, the current OperationContext is stored and the new OperationContext becomes the one returned by the Current property. Quando l'ambito OperationContextScope viene eliminato, il contesto originale OperationContext viene ripristinato.When the OperationContextScope is disposed, the original OperationContext is restored.

Avviso

Non usare il modello "await" asincrono in un blocco OperationContextScope.Do not use the asynchronous "await" pattern within a OperationContextScope block. Quando si verifica la continuazione, può essere eseguita su un thread diverso e OperationContextScope è specifico del thread.When the continuation occurs, it may run on a different thread and OperationContextScope is thread specific. Se è necessario chiamare "await" per una chiamata asincrona, usarlo all'esterno del blocco OperationContextScope.If you need to call "await" for an async call, use it outside of the OperationContextScope block.

Costruttori

OperationContextScope(IContextChannel)

Consente di inizializzare una nuova istanza della classe OperationContextScope che utilizza l'interfaccia IContextChannel specificata per creare un nuovo contesto OperationContext dell'ambito.Initializes a new instance of the OperationContextScope class that uses the specified IContextChannel to create a new OperationContext for the scope.

OperationContextScope(OperationContext)

Consente di inizializzare una nuova istanza della classe OperationContextScope per creare un ambito dell'oggetto OperationContext specificato.Initializes a new instance of the OperationContextScope class to create a scope for the specified OperationContext object.

Metodi

Dispose()

Consente di ripristinare il contesto OperationContext originale al contesto attivo e di riciclare l'oggetto OperationContextScope.Restores the original OperationContext to the active context and recycles the OperationContextScope object.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.Serves as the default hash function.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.Gets the Type of the current instance.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.Returns a string that represents the current object.

(Ereditato da Object)

Si applica a