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!

7 comments:

Anonymous said...

Your XML is wrong. Should look like this:

Alex said...

Thank your for the comment! I guess you talk about the baseAddresses tag. Was a typo :) I've updated the post.

Anonymous said...

brilliant! thanks!

Anonymous said...

Thank you very much, that saved me

Anonymous said...

Took me a while to find this! You are amazing. I wish your children and your children's children the ability to lure women to their bedside with no more than the blink of an eye.

Anonymous said...

Can we use the same if we want to expose the service via public fqdn on https?

Farih said...

Reallly,,, workk... thanks you so much..