Is to possible to add a custom behavior in the channel factory created by MetadataExchangeClient?

For example, is it possible to hook a message inspector to the MetadataExchangeClient  so that generated message can be inspected/logged?

 

It turns that default ctor of MetadataExchangeClient picks the endpoint information (including behavior configuration) from the config file. You can easily achieve this by creating a behavior extension and using it on MEX endpoint. Here are steps:

Step 1: create appropriate config entries

<system.serviceModel>

  <client>

    <endpoint address="http://localhost:9090/mex" binding="mexHttpBinding" contract="IMetadataExchange" behaviorConfiguration="epBv"/>

  </client>

  <behaviors>

    <endpointBehaviors>

      <behavior name="epBv">

        <customBehaviorToEnableMessageLogging/>

      </behavior>

    </endpointBehaviors>

  </behaviors>

</system.serviceModel>

Step2: Create a behavior extension 

public class customBehaviorToEnableMessageLogging : BehaviorExtensionElement

{

    public override Type BehaviorType

    {

        get { return typeof(InspectorInstallerBehavior); }

    }

 

    protected override object CreateBehavior()

    {

        return new InspectorInstallerBehavior();

    }

}

Step3: Create an endpoint behavior to install the message inspector

 

public class InspectorInstallerBehavior : IEndpointBehavior

{

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)

    {

        clientRuntime.MessageInspectors.Add(new MyInspector());

    }

}