Louis Rhys
Louis Rhys

Reputation: 35637

How to close a WCF service cleanly without cluttering your code?

Reading the accepted answer to this question, apparently the right way to use a WCF service is like this (copied with some modification)

// create your client
CustomerClient channel = CreateCustomerClient();

try
{
   // use it
   channel.GetCustomerDetails() ....

   (more calls)

   // close it
   channel.Close();
}
catch(CommunicationException commEx)
{
   // a CommunicationException probably indicates something went wrong 
   // when closing the channel --> abort it
   channel.Abort();
}

However, if my program use the service many times, this will clutter my code a lot. What is the clean way to do this without cluttering my code? Some ideas using lambda expression come to my mind, but so far they don't feel quite clean.

Upvotes: 0

Views: 183

Answers (1)

Ethan Cabiac
Ethan Cabiac

Reputation: 4993

The post you referenced has an Answer which references a post by Marc Gravell which uses an extension method so your WCF calls can be made to look something like this:

using (var client = new Proxy().Wrap()) {
    client.BaseObject.SomeMethod();
}

Upvotes: 1

Related Questions