I have a bunch of remote machines all running the same WCF service over HTTP. I have a central configuration utility that needs to decide at runtime which of these to connect to. I do not want to define all the endpoints in the configuration file because this is all database driven.
I naively tried this:
CustomerServiceClient GetClientForIPAddress(string ipAddress)
{
string address = String.Format("http://{0}/customerservice.svc", ipAddress);
var client = new CustomerServiceClient("?", address);
return client;
}
where CustomerServiceClient is my service reference proxy class, but (unsurprisingly) it gave me the following error:
Could not find endpoint element with name '?' and contract 'SkyWalkerCustomerService.ICustomerService' in the ServiceMod开发者_开发知识库el client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.
So how do I declare an endpoint at runtime and point my service reference to it?
.NET 3.5
This is a piece of code i use to configure my endpoints in a silverlight app:
private void initEndpoint(ServiceEndpoint endPoint, string serviceName)
{
Uri hostUri = Application.Current.Host.Source;
string vdir = hostUri.LocalPath.Substring(0, hostUri.LocalPath.IndexOf("/ClientBin", StringComparison.InvariantCultureIgnoreCase));
string wcfBaseUri = string.Format("{0}://{1}:{2}{3}/WebServices/", hostUri.Scheme, hostUri.Host, hostUri.Port, vdir);
endPoint.Address = new EndpointAddress(new Uri(wcfBaseUri + serviceName));
}
The endPoint passed in is the endpoint to be configured, and serviceName is the name of a service, like MyLoggingService.svc. All i do is point it at a new address (in this case a known location within the hosting website). Use this as a sample, and just pass in your own string addresses from where-ever.
It is called with a bit of code that looks like this:
_loggingService = new LoggingServiceClient();
initEndpoint(_loggingService.Endpoint, "LoggingService.svc");
Hope this helps. Take it and run with it, chop it up and make it your own :)
精彩评论