Sunday, February 3, 2013

WCF CommunicationObjectFaultedException - The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

WCF CommunicationObjectFaultedException -  The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

Due to some unhandled exception  or some protocol exception, network issue or binding issue like timeout etc, A channel can be faulted.

If you do not close or abort the channel in your client, you wont be able to call the service operation unless your reestablished a new communication channel between your service and client.
Any subsequent call through this faulted channel will let your Service Fault or Communication Fault exception

To avoid this faulted Exception, follow the basic approach .

1. use the Abort() method to dispose the faulted service proxy instead of calling close() method.

2. Avoid to use the using pattern to create the service proxy and follow the below pattern to create and dispose the service proxy.


           CaseServiceClient proxy = ServiceProxyManager.CreateProxy();
            try
            {
                 
             }
            finally
            {
                ServiceProxyManager.DisposeProxy(proxy);
            }

Under DisposeProxy()  method, before disposing the service proxy , we check the proxy status and according to this, we use Abort() or Close() method to dispose the service proxy


public static class  ServiceProxyManager
{
        public static void DisposeProxy(T obj)
        {
            try
            {
                if (obj != null)
                {
                    Type t = obj.GetType();
                    MethodInfo closeMethod = t.GetMethod("Close");
                    MethodInfo abortMethod = t.GetMethod("Abort");
                    PropertyInfo property = t.GetProperty("State");
                    if (property.GetValue(obj, null).ToString().Equals(CommunicationState.Faulted))
                    {
                        abortMethod.Invoke(obj, null);
                    }
                    else
                    {
                        closeMethod.Invoke(obj, null);
                    }
                }
            }
            catch (Exception ex)
            {
                UIExceptionHandler.HandleException(ex);
            }
        }




Suggested best practices for WCF  in my previous blog

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...