How can I change the address of a WCF service refe

2019-06-25 15:10发布

问题:

I have an application which is used internally and uses WCF for communication between client and server portions, however it will soon need deploying to sites where server names are different. The WCF services are hosted as a Windows service using the netTcp binding. At the moment, the addresses of the services are specified using the Add Service Reference command in Visual Studio.

Is it possible to make the base address of the WCF services a user preference, and then make the service reference dynamically construct the URL when it needs to use.

So for example, if I had a service named "CustomerService", is it possible for two separate users in different places to specify the addresses:

net-tcp://myserver1/

and

net-tcp://anotherserver/

and have the service reference convert these as necessary into

net-tcp://myserver1/CustomerService

and

net-tcp://anotherserver/CustomerService?

Thanks,

Jim

回答1:

When you instantiate the client proxy class (the one that derives from ClientBase and implements your service contract) you can specify a remote address:

var client = new MyServiceClient(
    "endpointConfigurationName", 
    "net-tcp://myserver1/CustomerService");

This way you can override the address value stored in your app/web.config

Another option if you use directly the ChannelFactory<T> class:

var factory = new ChannelFactory<IMyServiceContract>(
    "endpointConfigurationName", 
    new EndpointAddress("net-tcp://myserver1/CustomerService"));
IMyServiceContract proxy = factory.CreateChannel();


回答2:

Isn't all of this information in the configuration in the app.config or web.config? Simply change the URL in the endpoint configuration.