Wcf – How to force a net.tcp mex endpoint (mexTcpBinding) to participate in port sharing

mex-bindingsnet.tcpwcf

I have a WCF service which is hosted as a Windows Service. We would like to enable a mex endpoint at the same address (but with a '/mex' suffix). I have been trying to do this (unsuccessfully) using the following configuration:

<system.serviceModel>

  <services>
    <service
      name="MyCompany.MyService"
      behaviorConfiguration="defaultServiceBehavior">

      <host>
        <baseAddresses>
          <add baseAddress="net.tcp://localhost"/>
        </baseAddresses>
      </host>

      <endpoint
        address="MyService"
        binding="netTcpBinding"
        contract="MyCompany.IMyService"
        bindingConfiguration="netTcpBindingConfig"
        />

      <endpoint
        address="MyService/mex"
        binding="mexTcpBinding"
        contract="IMetadataExchange"
        />

    </service>
  </services>

  <behaviors>
    <serviceBehaviors>
      <behavior name="defaultServiceBehavior">
        <serviceMetadata />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <bindings>
    <netTcpBinding>
      <binding name="netTcpBindingConfig" portSharingEnabled="true" />
    </netTcpBinding>
  </bindings>

</system.serviceModel>

When it runs, the service host throws an AddressAlreadyInUseException complaining that "There is already a listener on IP endpoint 0.0.0.0:808". This actually makes sense to me because the port sharing service has opened that port in order to serve the MyService endpoint along with any other services requesting to share that port on this machine.

So it seems that the mex endpoint wants exlusive access to port 808. I can work around this by tweaking the mex endpoint like so:

<endpoint
  address="net.tcp://localhost:818/MyService/mex"
  binding="mexTcpBinding"
  contract="IMetadataExchange"
  />

This means that the mex endpoint now has its own exclusive port. The downside with this is that any other service which wants to expose a mex endpoint will also need a unique port for its mex endpoint. This makes it very unpredictable when looking for mex endpoints.

Is there a way to force the mex endpoint to participate in port sharing?

Best Answer

Two options:

  1. The easy way: Change the entire binding for the mex point to netTcpBinding and have it reuse your bindingConfiguration. mexTCPBinding is only meant to be a convenience and is optional. If its not working for you, don’t use it.

  2. The hard way: You can modify the mexTCPBinding to enable sharing. The only example I’ve seen is in code here: http://blogs.msdn.com/b/drnick/archive/2006/08/23/713297.aspx