2010-05-31 106 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");