Monday, January 18, 2010

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

While working on a WCF service, I ran into the following error.

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

This occurred when called Close method on instance of my WCF service client object. For a moment it took me by surprise. The code has been working fine and I was doing the right thing of closing connection to my WCF service after I was done using it. When I looked at the stack trace, I realized that it got thrown from a finally block of a method where I was calling a method on my WCF object. And before that there was an exception thrown. After further investigation it turned out that my WCF service was not running. So when I called method on the object, I got EndpointNotFoundException exception thrown when method was called. And in the same exception handling block I tried to call Close on client object. Since the client was already in bad state so next exception was thrown. So as a best practice, before you call Close method on your service object, check if its in Open state or not. This is exactly like a database connection object where you can check if its in open state or not. The following code snippet shows the change that I made to check for state of the WCF client object.


if (_serviceClient.State == CommunicationState.Opened)
{
_serviceClient.Close();
}

No comments:

Post a Comment