OperationContext Kelas

Definisi

Menyediakan akses ke konteks eksekusi metode layanan.

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)
Warisan
OperationContext
Penerapan

Contoh

Contoh kode berikut menggunakan Current properti dan GetCallbackChannel metode untuk mendapatkan saluran kembali ke pemanggil dari dalam metode . Semua metode dalam contoh ini adalah metode satu arah, memungkinkan layanan dan klien untuk berkomunikasi di kedua arah secara independen. Dalam hal ini, contoh aplikasi klien hanya mengharapkan satu panggilan pengembalian sebelum keluar, tetapi klien lain, misalnya klien Formulir Windows, dapat menerima sejumlah panggilan dari layanan.

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

Klien berikut mengimplementasikan SampleDuplexHelloCallback untuk menerima pesan panggilan balik. Kontrak panggilan balik yang diimpor bukan nama yang sama dengan yang ada di layanan, karena penggunaan Name properti dalam contoh sebelumnya. Perhatikan bahwa klien tidak membuat asumsi tentang apakah atau kapan klien mungkin menerima panggilan balik; panggilan balik server sepenuhnya independen dari panggilan keluar klien.

Catatan

Untuk contoh yang menggunakan OperationContext kelas dalam skenario klien, lihat 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

Keterangan

OperationContext Gunakan dari dalam operasi layanan untuk mengakses lingkungan eksekusi operasi saat ini. Secara khusus, konteks operasi digunakan untuk mengakses saluran panggilan balik dalam layanan dupleks, untuk menyimpan data status ekstra di seluruh bagian operasi, dan untuk mengakses header dan properti pesan masuk serta menambahkan header dan properti pesan keluar.

Untuk informasi selengkapnya tentang menggunakan ekstensi untuk menyimpan data status, lihat Objek yang Dapat Diperluas.

OperationContext memiliki properti dan metode berikut.

Konstruktor

OperationContext(IContextChannel)

Menginisialisasi instans OperationContext baru kelas yang menggunakan yang ditentukan IContextChannel dalam aplikasi klien.

Properti

Channel

Mendapatkan saluran yang terkait dengan objek saat ini OperationContext .

ClaimsPrincipal

Mendapatkan prinsipal berbasis klaim yang terkait dengan operasi.

Current

Mendapatkan atau mengatur konteks eksekusi untuk utas saat ini.

EndpointDispatcher

Mendapatkan atau mengatur dispatcher titik akhir untuk titik akhir untuk memeriksa atau memodifikasi.

Extensions

Mendapatkan kumpulan ekstensi layanan dari konteks pesan saat ini.

HasSupportingTokens

Mendapatkan nilai yang menunjukkan apakah pesan masuk memiliki token pendukung.

Host

ServiceHost Mendapatkan untuk objek layanan saat ini.

IncomingMessageHeaders

Mendapatkan header pesan masuk untuk OperationContext.

IncomingMessageProperties

Mendapatkan properti pesan untuk pesan masuk di OperationContext.

IncomingMessageVersion

Mendapatkan versi pesan SOAP masuk untuk OperationContext.

InstanceContext

InstanceContext Mendapatkan objek yang mengelola instans layanan saat ini.

IsUserContext

Properti ini ditujukan untuk penggunaan sistem dan tidak boleh dipanggil oleh pengguna.

OutgoingMessageHeaders

Mendapatkan header pesan keluar untuk yang aktif OperationContext.

OutgoingMessageProperties

Mendapatkan properti pesan untuk pesan keluar di aktif OperationContext.

RequestContext

Mendapatkan atau mengatur RequestContext implementasi untuk metode ini.

ServiceSecurityContext

Mendapatkan atau mengatur di ServiceSecurityContext mana metode ini dijalankan.

SessionId

Mendapatkan yang String digunakan untuk mengidentifikasi sesi saat ini.

SupportingTokens

ICollection<T> Mendapatkan jenis SecurityToken.

Metode

Equals(Object)

Menentukan apakah objek yang ditentukan sama dengan objek saat ini.

(Diperoleh dari Object)
GetCallbackChannel<T>()

Mendapatkan saluran ke instans klien yang memanggil operasi saat ini.

GetHashCode()

Berfungsi sebagai fungsi hash default.

(Diperoleh dari Object)
GetType()

Mendapatkan dari instans Type saat ini.

(Diperoleh dari Object)
MemberwiseClone()

Membuat salinan dangkal dari saat ini Object.

(Diperoleh dari Object)
SetTransactionComplete()

Menerapkan transaksi yang sedang dijalankan.

ToString()

Mengembalikan string yang mewakili objek saat ini.

(Diperoleh dari Object)

Acara

OperationCompleted

Terjadi ketika operasi telah selesai.

Berlaku untuk