Why "using" may play tricks on your WCF service host

Many of the examples that have been published on the web about hosting the WCF use the "using" block to initialize the service. This blog entry shows you why this can catch you.

The problem arises when you try to open your host and there is a problem with the configuration file, if you were coding with “using” and you try to catch an exception you will find the familiar meaningless message:

“The communication object, System.ServiceModel.ServiceHost, cannot be used for communication because it is in the Faulted state.”

The next step is to go to the configuration file and play around with the parameters until you find which one is causing the hassle. You fix it and life goes on... but what does this message mean?

Well, during this process we were missing an important piece of information, if you check the Output window you will find that actually are two exceptions:

“System.InvalidOperationExceptoin”
and
“System.ServiceModel.CommunicationObjectFaultedException”

Indeed, if you remove your error trapping and run the code you will get the first exception, and guess what? It contains the useful information regarding the problem with the configuration file. But why you don’t catch it with your try/catch block? The problem is on the “using” block.

The using block is a try/finally implementation, this means that if an exception occurs it will execute the finally and then it will be thrown to the next exception block. Reading this you should think “aha! But why is not appearing on my exception control?”

The answer to this is the nature of the second exception, this one is not thrown because of your configuration file, it is thrown because the finally statement of the “using” block is failing. If we write the same code as the “using” you will see:

ServiceHost Host = null;

try

{

       Host = new ServiceHost(MySingletonService);

       Host.Open();

       Console.ReadKey();

       Host.Close();

}

finally

{

       if (Host != null)

              ((IDisposable)Host).Dispose();

}

The configuration exception is thrown by the “Host.Open()” line, the code jumps into the finally block and tries to dispose the host. Here the host is not null but it is in a faulty state, this means that it cannot be disposed and this raises the second exception that you usually see on your application.