2010-03-23 75 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"); 

希望這有助於。把它和它一起運行,把它砍下來,讓它成爲你自己的:)