如何以编程方式将客户端连接到 WCF 服务?

问题描述:

我正在尝试将应用程序(客户端)连接到公开的 WCF 服务,但不是通过应用程序配置文件,而是通过代码.

I'm trying to connect an application (the client) to an exposed WCF service, but not through the application configuration file, but in code.

我应该怎么做?

您必须使用 ChannelFactory 类.

这是一个例子:

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

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

相关资源: