Alex Rivera | Logout

How to programmatically connect a client to a WCF service?

Asked 2010-05-31T11:17:51.397
75

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

How should I go about doing this?

Edit
Report

1 Answer

117

You'll have to use the ChannelFactory class.

Here's an example:

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();
    }
}

Related resources:

answered 2010-05-31T11:31:09.873

Your Answer