How to programmatically connect a client to a WCF service?
Solution 1:
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:
- How to: Use the ChannelFactory
Solution 2:
You can also do what the "Service Reference" generated code does
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");