C# – WCF client proxy initialization

cchannelwcf

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 a 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 the .Net framework 3.5 SP1, basicHttp binding with little customization.

Best Answer

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

Related Topic