This Chat is read-only. Login to resume chatting.
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();
}
}
}
}using (var consumer = new WcfApiConsumer())
{
consumer.Connect("username", "password");
var result = consumer.CallServiceMethod(client => client.YourWcfMethod(parameter1, parameter2));
}