Nov 9, 2009

Generic Client for WCF


While working on WCF i got frustrated working with the proxy auto-generated by VS2008.  While I loved creating the client channels using a ChannelFactory, i really got tired of writing:

ICommunicationObject
c = Client as ICommunicationObject;
if (c.State == CommunicationState.Faulted)
c.Abort();
else if (c.State != CommunicationState.Closed)
c.Close(); 


after every remoting call.  I searched for ever trying to find an easy way to close up the channel gracefully,
and nothing really stood out.  I really love the using statement pattern as I dont have to call Close(), but if the channel is in a faulted state you get an exception thrown.  I resorted to writing this generic class which isnt exactly pretty, but it gets the job done.



public class RemotingClient:IDisposable
{
public RemotingClient(ChannelFactory factory)
{
Client = factory.CreateChannel();

ICommunicationObject c = Client as ICommunicationObject;

if(null ==c)
throw new ArgumentException(typeof(T).GetType().ToString()
"Can not be used as an ICommunicationObject");

c.Open();
}


public T Client
{ getset; }


#region

//IDisposable Members


public void
Dispose()

{
ICommunicationObject c = Client as ICommunicationObject;

if(c.State == CommunicationState.Faulted)
c.Abort();
else if (c.State != CommunicationState.Closed)
c.Close();


}
#endregion

}
Now I can use my client in a fashion such as:


using(RemotingClient c = new RemotingClient(_channelfactory))
{

c.Client.SomeMethod();
}
and everything takes care of itself.  But for some reason having a class inherit from IDisposable just to take care of the channel doesnt feel right.  If there are any suggestions for a cleaner way I would love to hear it.

No comments:

Post a Comment