Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding config file WCF Base Addresses in code

I have a WCF Windows service with an endpoint specified in the config file for the service.

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

All works ok. However, in some cases port 9000 might already be in use which causes the ServiceHost to fall over on Open(). I need to be able to OVERRIDE the default base address specified in the config file in code. e.g. assume an environment variable contains the port number to be used.

Is there any way to do this programmatically?

After the ServiceHost is constructed I can see the BaseAddresses property which returns the Uri list taken from the config file. However, this is a read only collection so can't be used to change the defaults.

If I specify a replacement Uri in the ServiceHost constructor I get

This collection already contains an address with scheme net.tcp. There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'.

If I create a CustomServiceHost and try and set the replacement base address I get the same error.

class CustomHost : ServiceHost
{
    public CustomHost(Type serviceType) : base (serviceType)         
    {
    }
    protected override void ApplyConfiguration()
    {
        base.ApplyConfiguration();

        this.AddBaseAddress(new Uri("net.tcp://localhost:9010/MyEndpoint"));
    }
}

I know that if I leave the config file base addresses blank and pass the base address into the ServiceHost constructor then that works fine - i.e. I can specify the new bases. However, I want to use the config file to specify the default (instead of hard coding).

like image 489
Mark D Jackson Avatar asked Jun 21 '10 15:06

Mark D Jackson


1 Answers

Take a look at this example I posted. It has an entire working example of a WCF service configured completely via code. You should be able to then just grab the port number using Environment.GetEnvironmentVariable and pass it into the constructor of the ServiceHost:

Possible to have same contract, same binding, same address, but different ports?

like image 79
Flesrouy Avatar answered Sep 25 '22 11:09

Flesrouy