We have been diving deep into WCF lately. WCF is very nice to use, and a great alternative to web services. One of the things we are doing is dynamic WCF services where services can be created at run time of the web application (highly modified version of BinaryCoder's source listed on the MSDN website).
Anyhow, we are making reference to WCF interfaces that are hosted via IIS, and not wanting to generate the dirty proxy code that you need to do with web services.
This is a great snippet - the original is: http://blog.weminuche.net/
Our changes were to fit our design, which was a different constructor where we passed the URI of the service, and the receive message size because some of the data results that were passed back were larger then the default window.
/// <summary>
/// Generic Service Proxy for WCF - Connect to a URI/L with a type interface.
/// </summary>
/// <typeparam name="TInterface"></typeparam>
public class ServiceProxy<TInterface> : ClientBase<TInterface>, IDisposable where TInterface : class
{
#region Delegates
public delegate void ServiceProxyDelegate<T>(TInterface proxy);
#endregion
public ServiceProxy()
: base(typeof (TInterface).ToString())
{
}
/// <summary>
/// Pass the URI directly to the constructor.
/// </summary>
/// <param name="uri"></param>
public ServiceProxy(string uri)
: base(new BasicHttpBinding(){MaxReceivedMessageSize = int.MaxValue}, new EndpointAddress(uri))
{
}
public TInterface Proxy
{
get { return Channel; }
}
#region IDisposable Members
public void Dispose()
{
if (State == CommunicationState.Faulted)
{
base.Abort();
}
else
{
try
{
base.Close();
}
catch
{
base.Abort();
}
}
}
#endregion
protected override TInterface CreateChannel()
{
return base.CreateChannel();
}
public static void Call(ServiceProxyDelegate<TInterface> proxyDelegate)
{
Call(proxyDelegate, typeof (TInterface).ToString());
}
public static void Call(ServiceProxyDelegate<TInterface> proxyDelegate, string endpointConfigurationName)
{
var channel = new ChannelFactory<TInterface>(endpointConfigurationName);
try
{
proxyDelegate(channel.CreateChannel());
}
finally
{
if (channel.State == CommunicationState.Faulted)
{
channel.Abort();
}
else
{
try
{
channel.Close();
}
catch
{
channel.Abort();
}
}
}
}
}
Usage is very simple:
using (var client = new ServiceProxy<IModuleServices>(someURI))
{
var md = client.Proxy.ModuleDetailsGet(packet.UserSession.SessionID, packet.ModuleInstalledID);
return md.ReturnValue;
}