2015-08-28 87 views
4

可能這是非常愚蠢的,但做了谷歌很多,無法達成任何結論。ChannelFactory.CreateChannel()是否實際打開連接?

我想知道「ChannelFactory.CreateChannel()是否實際打開連接,或者它只是返回一些東西,實際的連接將會打開方法調用的時間,如果我不關閉它,這個連接還活着多久。 「

回答

4

好問題。當我想知道這樣的事情時,我只是在閱讀.Net的源代碼there

CreateChannel方法在內部調用Open方法。如果CommunicationState不等於OpenedOpen方法執行DefaultOpenTimeout

DefaultOpenTimeout通過端點綁定配置進行配置。您可以看到source code

+0

謝謝!這有幫助。 – Abhash786

2

只有在ChannelFactory中調用open()時纔會打開連接。 它是體現在這裏「https://msdn.microsoft.com/en-us/library/ms575250(v=vs.110).aspx

+0

我試過這個例子......但我怎麼能從這個通道調用我的服務(它是IRequestChannel類型)。 – Abhash786

+0

這裏是代碼示例 var binding = new CustomBinding(「CustomNetTcpBinding」); var factory = binding.BuildChannelFactory (binding,myEndpoint); factory.Open(); var channel = factory.CreateChannel(myEndpoint); var data = GenerateParameters(); channel.Open(); – Abhash786

+0

我不想動態地生成消息。 – Abhash786

1

實例部分它認爲你只需要創建此:

// Sample service 
public class Service : IService 
{ 
    public void SendMessage(string message) 
    { 
     // do the processing.... 
    } 
} 

// Creating client connection using factory 
// I can't remember the used of my asterisk here but this is use to identity the configuration name used for the endpoint. 
var result = new ChannelFactory<IService>("*", new EndpointAddress(serviceAddress)); 
IService yourService = result.CreateChannel(); 

// This will automatically open a connection for you. 
yourService.SendMessage("It works!"); 

// Close connection 
result.Close(); 

只是有點多個端點我的客戶端配置:

<client> 
     <!--note that there is no address on the endpoints as it will be overridden by the app anyway--> 
     <endpoint binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" behaviorConfiguration="standardBehavior" contract="IService" name="Service"/> 
     . 
     . 
</client> 

我使用這種方法給我的客戶端連接30個託管在IIS中的服務。順便說一下,我只是將這段代碼抓到現有的WCF服務中,並且實際的實現是,將ChannetFactory包裝到另一個方法中,我可以簡單地將我的服務作爲通用類型和服務地址傳遞。

我在這裏使用了消息模式Request Reply和.Net 4.5。

+0

感謝您的回覆。只是一個問題,如果我按照你提到的方式調用服務,將調用哪個服務方法。我看不出任何提及方法名稱的方法。提前致謝。 – Abhash786

+0

我通過'yourService.SendMessage(「It works!」);' – jtabuloc

+0

明明知道我叫'public void SendMessage(string message)'!感謝您的回覆 – Abhash786

相關問題