クライアントの動作の構成

Windows Communication Foundation (WCF) は 2 とおりの方法で動作を構成します。1 つは動作の構成を参照する方法で、これはクライアント アプリケーションの構成ファイルの <behavior> セクションで定義されます。もう 1 つは、呼び出し元アプリケーションでプログラムによって動作を構成する方法です。このトピックでは、両方の方法について説明します。

構成ファイルを使用する場合、動作の構成には、構成設定の名前付きコレクションがあります。各動作の構成には、一意の名前を指定する必要があります。この文字列をエンドポイントの構成の behaviorConfiguration 属性で使用し、エンドポイントと動作を関連付けます。

myBehavior という動作を定義する構成コードを次に示します。クライアント エンドポイントは、この動作を behaviorConfiguration 属性で参照します。

<configuration>
    <system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="myBehavior">
                    <clientVia />
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <bindings>
            <basicHttpBinding>
                <binding name="myBinding" maxReceivedMessageSize="10000" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="myAddress" binding="basicHttpBinding" bindingConfiguration="myBinding" behaviorConfiguration="myBehavior" contract="myContract" />
        </client>
    </system.serviceModel>
</configuration>

プログラムによる動作の使用

クライアントを開く前に、Windows Communication Foundation (WCF) クライアント オブジェクトまたはクライアント チャネル ファクトリ オブジェクト上の適切な Behaviors プロパティを見つけることで、動作をプログラムによって構成または挿入することもできます。

次のコード例は、チャネル オブジェクトの作成前に、Endpoint プロパティから返される ServiceEndpoint 上の Behaviors プロパティにアクセスすることで、プログラムでクライアント動作が挿入される方法を示します。

Public Class Client
  Public Shared Sub Main()
    Try
      ' Picks up configuration from the config file.
      Dim factory As New ChannelFactory(Of ISampleServiceChannel)("WSHttpBinding_ISampleService")

      ' Add the client side behavior programmatically to all created channels.
      factory.Endpoint.Behaviors.Add(New EndpointBehaviorMessageInspector())

      Dim wcfClientChannel As ISampleServiceChannel = factory.CreateChannel()

      ' Making calls.
      Console.WriteLine("Enter the greeting to send: ")
            Dim greeting As String = Console.ReadLine()
      Console.WriteLine("The service responded: " & wcfClientChannel.SampleMethod(greeting))

      Console.WriteLine("Press ENTER to exit:")
      Console.ReadLine()

      ' Done with service. 
      wcfClientChannel.Close()
      Console.WriteLine("Done!")
    Catch timeProblem As TimeoutException
      Console.WriteLine("The service operation timed out. " & timeProblem.Message)
      Console.Read()
    Catch fault As FaultException(Of SampleFault)
      Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage)
      Console.Read()
    Catch commProblem As CommunicationException
      Console.WriteLine("There was a communication problem. " & commProblem.Message)
      Console.Read()
    End Try
  End Sub

参照

その他のリソース

<behaviors>