Monday, February 7, 2011

Dynamic base address for a WCF service

Last week I've learned a nice 'trick' that allows to specify a dynamic base address for a WCF service in the configuration file. When you want to run a WCF service you need to specify the base address for the service host. You can do this in a config file or directly in your code when creating a ServiceHost instance: http://msdn.microsoft.com/en-us/library/ms733749.aspx.
Now if you are deploying your service to many machines you must either adjust the host name for each machine during/after the installation or you set the host name to 'localhost'. The problem with the last option is that if you are also exposing metadata then the MEX client will get some endpoint addresses with 'localhost' as host name and will try to call this service on its local machine unless you adjust the host name while creating a proxy.
A handy solution for this problem is to use a so called 'weak wildcard' for the host name part of the base address:
<system.serviceModel>
  <services>
    <host>
      <baseAddresses>
        <add baseaddress="net.tcp://*:1234/svc" />
      </baseAddresses>
    </host>
  </services>
</system.serviceModel>
That's it. The framework will replace the wild card with the name of the host the service is actually running on.
Edit: The solution works only with base-addresses not with endpoint addresses!