Configuring Client Behaviors

Windows Communication Foundation (WCF) configures behaviors in two ways: either by referring to behavior configurations -- which are defined in the <behavior> section of a client application configuration file – or programmatically in the calling application. This topic describes both approaches.

When using a configuration file, behavior configuration is a named collection of configuration settings. The name of each behavior configuration must be unique. This string is used in the behaviorConfiguration attribute of an endpoint configuration to link the endpoint to the behavior.


The following configuration code defines a behavior called myBehavior. The client endpoint references this behavior in the behaviorConfiguration attribute.

                <behavior name="myBehavior">
                    <clientVia />
                <binding name="myBinding" maxReceivedMessageSize="10000" />
            <endpoint address="myAddress" binding="basicHttpBinding" bindingConfiguration="myBinding" behaviorConfiguration=”myBehavior” contract="myContract" />

Using Behaviors Programmatically

You can also configure or insert behaviors programmatically by locating the appropriate Behaviors property on the Windows Communication Foundation (WCF) client object or on the client channel factory object prior to opening the client.


The following code example shows how to programmatically insert a behavior by accessing the Behaviors property on the ServiceEndpoint returned from the Endpoint property prior to the creation of the channel object.

public class Client
  public static void Main()
      // Picks up configuration from the config file.
      ChannelFactory<ISampleServiceChannel> factory 
        = new ChannelFactory<ISampleServiceChannel>("WSHttpBinding_ISampleService");

      // Add the client side behavior programmatically to all created channels.
      factory.Endpoint.Behaviors.Add(new EndpointBehaviorMessageInspector());

      ISampleServiceChannel wcfClientChannel = factory.CreateChannel();

      // Making calls.
      Console.WriteLine("Enter the greeting to send: ");
      string greeting = Console.ReadLine();
      Console.WriteLine("The service responded: " + wcfClientChannel.SampleMethod(greeting));

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

      // Done with service. 
    catch (TimeoutException timeProblem)
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
    catch (FaultException<SampleFault> fault)
      Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage);
    catch (CommunicationException commProblem)
      Console.WriteLine("There was a communication problem. " + commProblem.Message);

See Also

Other Resources


Community Additions