2010-05-31 42 views
70

我試圖將應用程序(客戶端)連接到公開的WCF服務,但不是通過應用程序配置文件,而是通過代碼連接。如何以編程方式將客戶端連接到WCF服務?

我應該怎麼做呢?

+1

對於任何搜索這件事,看看這樣的回答:http://stackoverflow.com/a/839941/592732 – MarioVW 2014-03-17 18:18:28

回答

101

您將不得不使用ChannelFactory類。

下面是一個例子:

var myBinding = new BasicHttpBinding(); 
var myEndpoint = new EndpointAddress("http://localhost/myservice"); 
var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint); 

IMyService client = null; 

try 
{ 
    client = myChannelFactory.CreateChannel(); 
    client.MyServiceOperation(); 
    ((ICommunicationObject)client).Close(); 
} 
catch 
{ 
    if (client != null) 
    { 
     ((ICommunicationObject)client).Abort(); 
    } 
} 

相關資源:

+3

太好了,謝謝。 作爲補充,下面是如何讓IMyService對象在您的應用程序中使用:http://msdn.microsoft.com/en-us/library/ms733133.aspx – Andrei 2010-05-31 12:46:03

+0

您應該將'client'強制轉換爲'IClientClient'爲了關閉它。 – Dyppl 2011-05-25 06:03:32

+0

在我的例子中,我假設'IMyService'接口繼承自[System.ServiceModel.ICommunicationObject](http://msdn.microsoft.com/en-us/library/system.servicemodel.icommunicationobject.aspx)。我修改了示例代碼以使其更清晰。 – 2011-05-25 09:58:03

6

你也可以做什麼 「服務引用」 生成的代碼確實

public class ServiceXClient : ClientBase<IServiceX>, IServiceX 
{ 
    public ServiceXClient() { } 

    public ServiceXClient(string endpointConfigurationName) : 
     base(endpointConfigurationName) { } 

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) : 
     base(endpointConfigurationName, remoteAddress) { } 

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) : 
     base(endpointConfigurationName, remoteAddress) { } 

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) : 
     base(binding, remoteAddress) { } 

    public bool ServiceXWork(string data, string otherParam) 
    { 
     return base.Channel.ServiceXWork(data, otherParam); 
    } 
} 

哪裏IServiceX是WCF服務合同

那麼你的客戶端代碼:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911")); 
client.ServiceXWork("data param", "otherParam param"); 
相關問題