What are the best practices for accessing a WCF web service from an ASP.NET application? Currently, in each page I need to access the service I have a field
private readonly _serviceClient = new WCFServiceClient();
and access it’s methods repeatedly, closing it on each call and creating a new instance everytime it’s state is Faulted. However, I don’t know whether I should do it like this or, instead, create a new instance per method call. What are the best practices regarding this?
I’ve done something similar to the article RubbleFord linked to in his comment, but since I was dealing with multiple services I used ChannelFactory and cached the returned object upon initial creation. I then would create new channels as needed, use them, then close/abort as needed. The helper methods are in a separate DLL (I’ll use Common for the example):
In my client code, I’d do something like this (with the helper methods in Common):
I developed this based on some articles posted on the web around a year ago, when I first started working with WCF, and it’s served me well. The OpenChannels dictionary object is stored (in my case, with the AppDomain as most of my WCF services are WCF libraries) so I only need to create each channel factory once during a given app’s lifetime.
You can add any necessary logic (for example, credentials, or different types of bindings) to the GetFactoryChannel method as desired. I should also note that I don’t add service references to the projects, but use the generated proxy files from svcutil. This is in 3.5, btw.