Overriding config file WCF Base Addresses in code
Asked Answered
E

1

7

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).

Erfurt answered 21/6, 2010 at 15:52 Comment(0)
L
5

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?

Lillianalillie answered 7/7, 2010 at 17:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.