user207809
user207809

Reputation: 61

dynamically set the base address of a WCF service in the client

I built a WCF service library and hosted it through a host application. Then I constructed a client application, but it seems that the address of the service host is hard coded in the client program. What if the host changes its address? Is it possible to write the client application so that the address of the host can be entered by the client at run time?

Upvotes: 1

Views: 758

Answers (1)

MoNsTeR
MoNsTeR

Reputation: 63

Yes, it's possible, if you write the WCF client proxy by hand, instead of generating it automatically with Visual Studio adding a service reference.

Let's start from this example (https://learn.microsoft.com/it-it/dotnet/framework/wcf/feature-details/how-to-use-the-channelfactory), just to understand how ChannelFactory works, and then modify it a little bit, adding the following function.

private ChannelFactory<IMath> _myChannelFactory;

// ...

private IMath GetChannel(string endpointConfigurationName, string endpointAddress)
{
    if (_myChannelFactory == null)
    {
        this.DebugLog("Channel factory is null, creating new one");
        if (String.IsNullOrEmpty(endpointAddress))
        {
            _myChannelFactory = new ChannelFactory<IMath>(endpointConfigurationName);
        }
        else
        {
            _myChannelFactory = new ChannelFactory<IMath>(endpointConfigurationName, new EndpointAddress(endpointAddress));
        }
    }
    return _myChannelFactory.CreateChannel();
}

You can define the default server IP in the client App.config file

<system.serviceModel>
    <!-- ... -->
    <client>      
        <endpoint address="net.tcp://192.168.10.55:81/math/" binding="netTcpBinding" 
                  bindingConfiguration="NetTcpBinding_IMath" 
                  contract="MyNamespace.IMath" name="NetTcpBinding_IMath" />      
    </client>
</system.serviceModel>

In this way, when GetChannel("NetTcpBinding_IMath", "net.tcp://127.0.0.1:81/math") is called, it picks up the endpoint configuration from App.config file, replacing the default address (192.168.10.55) with the new one (127.0.0.1).

Some more documentation about ChannelFactory: https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.channelfactory-1.createchannel?view=netframework-4.8

Upvotes: 1

Related Questions