tags:

views:

349

answers:

2

I am consuming a WCF service and created its proxy using the VS 2008 service reference.

I am looking for the best pattern to call WCF service method

  • Should I create the client proxy instance every time I call the service method and close the client as soon as I am done with that? When I profiled my client application, I could see that it is taking lot of time to get the Channel while initializing the proxy client
  • Should I use a Singleton pattern for the client proxy so that I can use the only once instance and get rid of the re-initializing overhead? Is there any hidden problem with this approach?

I am using .Net framework 3.5 SP1, basicHttp binding with little customization.

+3  A: 

It depends ;-)

If you have a sequence in your app that requires several calls after one another, you could hang on to the proxy client and keep using it to make further calls. Be warned though to check for the "faulted" state - if an error happens on the server, the channel between the client proxy and the server might "fault" and thus your client proxy becomes unusable.

Also - the expensive part is the creation of the ChannelFactory<T> - you could try to separate these two steps out when you create your client proyx in code:

ChannelFactory<IYourService> factory = new ChannelFactory<IYourService>();

Hang on to that channel factory, e.g. cache it somewhere

The second step should be much less intensive in terms of time and horsepower:

IYourService client = factory.CreateChannel();

You could do this step before every call (or call sequence) and shouldn't get bad performance out of that, really.

I would strongly recommend to avoid singletons whenever possible - it's like opening a can of worms, don't do it unless you absolutely, positively have to (e.g. to manage access to a single resource that's only available for one caller at a time).

Marc

marc_s
I agree with the approach of making a single factory instance, and not having singleton channel instances. For channels, use em and loose em, and be sure to close them properly, checking the faulted state.
rally25rs
A: 

Sorry for kicking up an old question, but I wanted to add this for easy reference.

I fully agree with marc_s and rally25rs. So start there, but also consider using a proxy or wrapper that handles faulted states. Here is a question on SO that discusses some solutions, and here is another good solution I came across on the internet by Corneliu, "Building a reusable ClientBase proxy". His solution generates wrappers that expose your service methods for maximum convenience and performance. I still have to test if it works though :).

Andre Luus