Thursday, February 4, 2010

WCF Client Proxy IDisposable - Generic WCF Service Proxy

public class ServiceProxy : ClientBase, IDisposable where TInterface : class
{
public delegate void ServiceProxyDelegate(TInterface proxy);

public ServiceProxy()
: base(typeof(TInterface).ToString())
{
}
public ServiceProxy(string endpointConfigurationName)
: base(endpointConfigurationName)
{
}

protected override TInterface CreateChannel()
{
return base.CreateChannel();
}

public TInterface Proxy
{
get
{
return this.Channel;
}
}

public static void Call(ServiceProxyDelegate proxyDelegate)
{
Call(proxyDelegate, typeof(TInterface).ToString());
}

public static void Call(ServiceProxyDelegate proxyDelegate, string endpointConfigurationName)
{
ChannelFactory channel = new ChannelFactory(endpointConfigurationName);

try
{
proxyDelegate(channel.CreateChannel());
}
finally
{
if (channel.State == CommunicationState.Faulted)
{
channel.Abort();
}
else
{
try
{
channel.Close();
}
catch
{
channel.Abort();
}
}
}
}

public void Dispose()
{
if (this.State == CommunicationState.Faulted)
{
base.Abort();
}
else
{
try
{
base.Close();
}
catch
{
base.Abort();
}
}
}
}

And, here are some usages samples...
//delegate example1
string response = null;
ServiceModel.ServiceProxy.Call(p =>
{
response = p.DoStuff("ServiceProxyUsingTest");
}
);

//delegate example2
string response = null;
ServiceProxy.Call(p => response = p.DoStuff("ServiceProxyUsingTest"));

//using example
string response = null;
using (ServiceProxy service = new ServiceProxy())
{
response = service.Proxy.DoStuff("ServiceProxyUsingTest");
}


Ref:http://blog.weminuche.net/2008/08/test-post.html
http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=5&tabid=11#WCFContracts
http://www.dofactory.com/ShortCutKeys/ShortCutKeys.aspx

http://my.safaribooksonline.com/0130925691

No comments: