The power of WCF Behaviors 4 – Endpoint Behavior

The best usage of endpoint Behavior is still in exception shielding, to convert those Fault from server back to it’s original exception, by calling messageInspector in EndpointBehavior.

But using serviceClientFactory is much easier. We can just unwrap it.

ServiceClientFacotry

...
       public TResult CallService
(Func function)
        {
            Client client = CreateClient();
            TResult result = default(TResult);

            try
            {
                result = function(client.Service);
                if (client.State != CommunicationState.Faulted)
                {
                    client.Close();
                }
                else
                {
                    client.Abort();
                }
            }
            catch (Exception e)
            {
                client.Abort();
                HandleException(e);
            }

            return result;

        }

        public virtual void HandleException(Exception ex)
        {

            if (ex is FaultException && ex.GetType().IsGenericType)
            {
                var result = (Exception)ex.GetType().GetProperty("Detail").GetValue(ex, null);
                throw result;
            }

            throw ex;
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s