Here's a simple wrapper class in C# for consuming a WCF API using the System.ServiceModel namespace. This example assumes you have already added a Service Reference to your project and generated the necessary client and data contract classes.
using System;
using System.ServiceModel;
using System.ServiceModel.Security;
namespace WcfApiWrapper
{
public class WcfApiConsumer : IDisposable
{
private readonly ClientBase<IYourWcfService> _client;
public WcfApiConsumer()
{
_client = new ClientBase<IYourWcfService>();
}
public void Connect(string username, string password)
{
_client.ClientCredentials.UserName.UserName = username;
_client.ClientCredentials.UserName.Password = password;
// If the service uses HTTPS, you may need to set the security mode accordingly:
// _client.Endpoint.Binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
}
public T CallServiceMethod<T>(Func<IYourWcfService, T> method)
{
try
{
_client.Open();
return method(_client.Channel);
}
catch (Exception ex)
{
throw new ApplicationException($"Error while calling WCF service method: {ex.Message}", ex);
}
finally
{
if (_client.State != CommunicationState.Faulted)
{
_client.Close();
}
else
{
_client.Abort();
}
}
}
public void Dispose()
{
if (_client != null)
{
if (_client.State != CommunicationState.Closed)
{
_client.Close();
}
_client.Dispose();
}
}
}
}
To use this wrapper class, you would instantiate it, call the Connect method with the appropriate credentials, and then call the CallServiceMethod method with a lambda expression that invokes the desired method on the WCF service.
For example:
using (var consumer = new WcfApiConsumer())
{
consumer.Connect("username", "password");
var result = consumer.CallServiceMethod(client => client.YourWcfMethod(parameter1, parameter2));
}