Ben McCallum's Blog

Dissecting ASP.NET MVC3, CSS3, HTML5, jQuery and a whole lot of other things ending with numbers…

WCF Web Service Wrapper: Closing, Disposing and Aborting best practices

When calling methods on a WCF web service it’s best practise to do the following:
(To avoid the using keyword with WCF clients: http://msdn.microsoft.com/en-us/library/aa355056.aspx)

But all this garbage is exhausting and repetitive when you are calling the web service in many places.

One solution is to inherit IDisposable and implement Dispose() for the web service but you’ll need to do that for every web service you consume meaning more duplicate code and using partial classes in combination with the auto-generated code from your service reference in Visual Studio.

Instead, I’ve come up with a hybrid of many ideas on the web that essentially wraps the WCF web service, performs any method calls and closes/disposes/aborts the connection gracefully:

An example of usage:

It’s a very elegant, and highly re-usable piece of code that I’ll be using in all apps that consume WCF web services. Using generics the same Service class can make calls to different services meaning you can plug-n-play this code in all your client apps and never write a try catch finally block around WCF service calls again. And if you ever need to customise the way service calls are handled, errors logged, etc. it’s all in one spot! Enjoy!

Advertisement

Single Post Navigation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.