2

The simple case where my OperationContract implementation is like:

public List<Directory> GetDirectories(bool includeFiles)
{
    if (includeFiles)
    {
        return this.db.Directories.Include(e => e.Files).ToList();
    }
    else
    {
        return this.db.Directories.ToList();
    }
}

where GetDirectories(false); works perfectly ok and GetDirectories(true); throws a CommunicationObjectFaultedException with message:

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

Obviously my File entities have reference to Directory entities, and the Directory entities have a list of files. First I thought this would be the typical cyclic reference trap but I get no signs of it in the exception message. Any ideas on this problem?

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • Hm, CommunicationObjectFaultedException usually is not the first exception you should see (you get it after you break your channel and try to use it broken with next request), I think you should search where you're loosing first exception, it will contain actual information to solve problem. – Giedrius Sep 27 '11 at 08:58
  • Handling of first chance exceptions is enabled with the debugger and yet, CommunicationObjectFaultedException is the first exception that is thrown. In other cases, I would get exceptions regarding cyclic references but not this time. – Teoman Soygul Sep 27 '11 at 08:59
  • I'm still thinking there's one before faulted exception. Any custom error handling (if not, check event logs)? Also, you may try to make request using SoapUI, different platform may help you catch missing part. – Giedrius Sep 27 '11 at 09:05

1 Answers1

1

It will be cyclic reference trap (here is something about this topic) and reason for your CommunicationObjectFaultedException will be something like:

using (var client = new ServiceClient())
{
    data = client.GetDirectories(true);
}

The reason is that unhandled exception has faulted the channel and using is trying to call Close on that faulted channel - it is invalid transition in channel state machine (and one big WCF strangeness) resulting it the exception you mentioned. There are many ways to avoid it but the basis is:

ServiceClient client = null;

try
{
    client = new ServiceClient();
    data = client.GetDirectories(true);
}
finally
{
    if (client != null)
    {
        if (client.State == CommunicationState.Faulted) 
        {
            client.Abort();
        } 
        else 
        {
            client.Close();
        }
    }
}
Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Instant hit. Adding `[IgnoreDataMember]` to navigational property in File entity solves the problem. With your suggestion, now I see the real exceptions as a cyclic ref. so thanks for pointing that out. – Teoman Soygul Sep 27 '11 at 09:13