How to programmatically connect a client to the WCF service?

I am trying to connect an application (client) to an open WCF service, but not through the application configuration file, but into the code.

How should I do it?

+70
c # wcf wcf-binding wcf-client
May 31 '10 at 11:17
source share
2 answers

You will need to use the ChannelFactory class.

Here is an example:

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

Related Resources:

+100
May 31 '10 at 11:31 a.m.
source share

You can also do what the "Service Reference" code generated

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

Where IServiceX is your WCF Service Contract

Then your client code:

 var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911")); client.ServiceXWork("data param", "otherParam param"); 
+6
Feb 20 '15 at 0:26
source share



All Articles