Jaa


Setting client behaviors on a MEX connection

Most WCF developers will use MEX at some point in their projects. It is a convenient way to expose and consume metadata about your WCF service. Normally you can use the built-in MetadataExchangeClient class which was made specifically for consuming a MEX endpoint.

WCF provides you standard bindings for using MEX across the usual set of protocols, HTTP, HTTPS, TCP and named pipes. Here is an example of using the WSHttpBinding:

WSHttpBinding

mex = (WSHttpBinding)MetadataExchangeBindings.CreateMexHttpBinding(); MetadataExchangeClient mec = new MetadataExchangeClient(mex);

In most enterprises you often use custom bindings, so you can replace the binding above with your custom binding – as long as you are using the same custom binding with the service. However, where I hit a road block was in using custom client behaviors with MetadataExchangeClient. There does not seem to be any obvious way to attach behaviors to the outgoing MEX requests. After doing some experimentation, I realized that the MetadataExchangeClient class is extensible and the way to do this is to write a simple class that inherits from it and then override a couple of methods as follows:

public class MyMexClient : MetadataExchangeClient

{

   Binding MexBinding = null;

   bool RequiresClientCertificate = false;

 

   public MyMexClient(Binding b): base(b)

   {

       MexBinding = b;

   }

 

   public MyMexClient(Binding b)

       : base(b)

   {

       MexBinding = b;

   }

 

   protected override ChannelFactory<IMetadataExchange> GetChannelFactory(EndpointAddress metadataAddress, string dialect, string identifier)

   {

       ChannelFactory<IMetadataExchange> MexFactory = new ChannelFactory<IMetadataExchange>();

       MexFactory.Endpoint.Binding = MexBinding;

       MexFactory.Endpoint.Address = metadataAddress;

       // Add your client behavior here ...

       MexFactory.Endpoint.Behaviors.Add(SomeBehavior);

       return MexFactory;

   }

}

 

Now you simply use MyMexClient wherever you would normally use MetadataExchangeClient.

Comments