2010-03-23 76 views
3

我有一堆远程机器都通过HTTP运行相同的WCF服务。我有一个中央配置实用程序,需要在运行时决定连接哪些设备。我不想在配置文件中定义所有端点,因为这都是数据库驱动的。在运行时指定WCF端点的IP地址

我天真地想这:

CustomerServiceClient GetClientForIPAddress(string ipAddress) 
{ 
string address = String.Format("http://{0}/customerservice.svc", ipAddress); 
var client = new CustomerServiceClient("?", address); 
return client; 
} 

其中CustomerServiceClient是我的服务引用代理类,但(不出所料)它给了我下面的错误:

Could not find endpoint element with name '?' and contract 'SkyWalkerCustomerService.ICustomerService' in the ServiceModel 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.

那么,如何申报端点在运行时并将我的服务引用到它?

.NET 3.5

+0

我相信这是一个复制http://stackoverflow.com/questions/1978962/how-to-change-endpoint-address-programatically-在-的客户端站点 – 2010-03-23 08:40:03

回答

3

这是一段代码我使用配置我端点在一个Silverlight应用程序:

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)); 
    } 

端点传入是要配置的端点,和serviceName是服务的名称,如MyLoggingService.svc。我所做的只是将它指向一个新的地址(在这种情况下是托管网站中的已知位置)。以此作为示例,并从任何地方传入自己的字符串地址。

它被称为有一些代码,看起来像这样:

_loggingService = new LoggingServiceClient(); 
initEndpoint(_loggingService.Endpoint, "LoggingService.svc"); 

希望这有助于。把它和它一起运行,把它砍下来,让它成为你自己的:)