2012-08-31 45 views
3

所以我對WCF並不太熟悉,我所用的所有東西都沒有幫助我實現我所需要的東西。對不起,如果這是一個愚蠢的問題:)在wcf客戶端動態設置端點地址(使用net tcp綁定)

基本上有一個服務器應用程序暴露與WCF服務(淨tcp綁定)。我寫了一個新的控制檯應用程序,我需要調用該服務。所以我可以通過爲我們的代理項目添加一個dll並添加一堆配置文件(如WCFClientBindings,WCFClientEndPoints)來實現此目的。然而,應用程序應該能夠調用傳遞作爲命令行參數的主機名

using (var partyProxy = new PartyControllerProxy()) 
      { 
       // execute server method 
       partyProfile = partyProxy.GetLatestPartyProfile(context, parsedParameters.PartyId); 
      } 

:如果我用一個定義的結束點,然後我可以調用這樣的代碼。

因此,雖然我的應用支持定義端點:

<client> 
    <endpoint 
    name="IPartyControllerEndpoint" 
    address="net.tcp://localhost:46000/ServiceInterface/PartyController.svc" 
    binding="customBinding" bindingConfiguration="DefaultNetTcpBindingConfiguration" 
    contract="CompanyA.Service.Product.Core.Contracts.IPartyController" 
    behaviorConfiguration="DefaultEndpointBehavior"> 
    </endpoint> 
</client> 

我需要能夠更新本地主機的主機名是潛在別的東西。我希望安全不會讓我失望:)

我見過的例子似乎通過傳入「動態」綁定和地址來實例化客戶端/代理,但我們的代理類不接受這些。在調用「代理」類之前,沒有辦法更新端點的地址(在運行時)嗎?我見過的其他例子都涉及實例化一個新的ServiceHost - 但這聽起來不太適合客戶端:)

謝謝!

編輯 -好的這裏的語法似乎很好地工作。這與我接受的答案有點不同,但這種方法是要走的方式:)

using (ChannelFactory<IPartyController> factory = new ChannelFactory<IPartyController>("IPartyControllerEndpoint")) 
     { 
      EndpointAddress address = new EndpointAddress(String.Format("net.tcp://{0}/ServiceInterface/PartyController.svc", parsedParameters.HostName)); 
      IPartyController channel = factory.CreateChannel(address); 

      partyProfile = channel.GetLatestPartyProfile(context, parsedParameters.PartyId); 
      ((IClientChannel)channel).Close(); 
     } 

回答

5

您可以創建一個ChannelFactory。

除了標準客戶端,WCF WSDL還將爲客戶端提供接口類。

EndpointAddress address = new EndpointAddress("http://dynamic.address.here"); 
     using (ChannelFactory<IPartyControllerChannel> factory = new ChannelFactory<IPartyControllerChannel>("IPartyControllerEndpoint", address)) 
     { 

      using (IPartyControllerChannel channel = factory.CreateChannel()) 
      { 
       channel.GetLatestPartyProfile(context, parsedParameters.PartyId); 
      } 
     } 
+0

我打算將您的答案標記爲答案..並用我使用的語法更新我的問題。我看不到一個將字符串和端點地址作爲參數的CreateChannel構造函數 - 但是設法將其排除。感謝您指點我在正確的方向:) – Jen

+1

哈謝謝,我更新了我的代碼。我把地址初始化放在錯誤的地方。 :(你也可以通過EndpointAddress創建通道功能 – Brad

+0

酷 - 謝謝:) – Jen