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:
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!