Using IOperationInvoker in WCF For Global Exception Handling and Logging

In this article, we’ll discuss an Interceptor IOperationInvoker that can be used before and after activity when service actually calls it’s operations.

There are several ways to implement Global Exception Handling in WCF, for example using an IErrorHandler (the best way to handle the uncaught exceptions) or by creating your own Façade for calling all service methods. In this article, we'll discuss an Interceptor IOperationInvoker that can be used before and after activity when service actually calls its operations. There are several things you can perform at this stage, like Logging, Tracing or handling the exception (especially Unhandled Exceptions).
 
First we'll start to look at a high level of the picture where the operation invoker actually stands when a client makes a service method call. The following diagram shows a picture of that.
 
IOperationInvoker1.jpg 
 
So let's create a WCF service project. (Learn how to create and consume a WCF service.) After adding the project, we need to add some operation in the service so for example our service operation is GetParseData(). So it can look something like this, as generated from the project template.
 
IServiceContract
  1. [OperationContract]  
  2. string GetParseData(string value)  
Service.cs
  1. public string GetParseData(string value)  
  2. {  
  3.      return string.Format("You entered: {0}", value);  
  4. }  
To get some exceptions we'll use custom logic in the Implementation of GetParseData(). So it can look something like this.
  1. public string GetParseData(string value)  
  2. {  
  3.      // check if value is alphabets/Numeric  
  4.      if (string.IsNullOrEmpty(value))  
  5.      {  
  6.          throw new ArgumentException("Method parameter value can not be null or empty");  
  7.      }  
  8.    
  9.      // split the value if it contains spaces and return first two words  
  10.      var stringArray = value.Split(' ');  
  11.    
  12.      // This will/may cause an Unhandled exception for OutOfIndex in case of single word is passed.  
  13.      return string.Format("{0}_{1}_{2} ..", stringArray[0], stringArray[1], stringArray[2]);  
  14. }  
Here in this method we have introduced some known and unhandled exceptions. To demonstrate the logging and Global Exception Handling we'll now create a class that will Implement the IOperationInvoker interface.
  1. /// <summary>  
  2. /// Global error handler of service operations using IOperationInvoker  
  3. /// </summary>  
  4. public class ErrorHandlingLoggingOperationInvoker : IOperationInvoker  
  5. {  
  6.     private readonly ILog logger;  
  7.     private IOperationInvoker invoker;  
  8.     private string operationName;  
  9.   
  10.     public ErrorHandlingLoggingOperationInvoker(IOperationInvoker baseInvoker, DispatchOperation operation)  
  11.     {  
  12.         this.invoker = baseInvoker;  
  13.         this.operationName = operation.Name;  
  14.         XmlConfigurator.Configure();  
  15.         logger = LogManager.GetLogger("serviceLogger");  
  16.     }  
  17.   
  18.     public bool IsSynchronous  
  19.     {  
  20.         get  
  21.         {  
  22.             return true;  
  23.         }  
  24.     }  
  25.   
  26.     public object[] AllocateInputs()  
  27.     {  
  28.         return this.invoker.AllocateInputs();  
  29.     }  
  30.   
  31.     //This is our intent method to intercept the request.  
  32.     public object Invoke(object instance, object[] inputs, out object[] outputs)  
  33.     {  
  34.         logger.InfoFormat("Start command operation:{0}"this.operationName);  
  35.         object result = null;  
  36.         try  
  37.         {  
  38.             result = this.invoker.Invoke(instance, inputs, out outputs);  
  39.         }  
  40.         catch (Exception exception)  
  41.         {  
  42.             logger.Error("Unhandled Exception: ", exception);  
  43.             outputs = new object[] { };  
  44.   
  45.             throw new FaultException(new FaultReason(exception.Message));  
  46.         }  
  47.         logger.InfoFormat("End command operation:{0}"this.operationName);  
  48.         return result;  
  49.     }  
  50.   
  51.     public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)  
  52.     {  
  53.         throw new Exception("The operation invoker is not asynchronous.");  
  54.     }  
  55.   
  56.     public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)  
  57.     {  
  58.         throw new Exception("The operation invoker is not asynchronous.");  
  59.     }  
  60. }  
In this implementation of IOperationInvoker we will only focus on the Invoke() method to log the request begin and request end. Also a Try Catch block is placed on the invoke statement so that we can capture any unhandled exception and log it in the first place with all details. And we're not sending the complete exception to the client but a custom FaultException with less details or a message.
 
Now the invoker is ready but how to attach this Invoker/Dispatcher to our service. For this we'll implement the IOperationBehavior first to attach the invoker with default operation behaviors.
  1. /// <summary>  
  2. /// Behavior defined for global exception handler  
  3. /// </summary>  
  4. public class GlobalExceptionHandlerBehavior : IOperationBehavior  
  5. {  
  6.     public void Validate(OperationDescription operationDescription)  
  7.     {  
  8.         return;  
  9.     }  
  10.   
  11.     public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)  
  12.     {// Here we have added our invoker to the dispatch operation        dispatchOperation.Invoker = new ErrorHandlingLoggingOperationInvoker(dispatchOperation.Invoker, dispatchOperation);  
  13.     }  
  14.   
  15.     public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)  
  16.     {  
  17.         return;  
  18.     }  
  19.   
  20.     public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)  
  21.     {  
  22.         return;  
  23.     }  
  24. }  
Now we have our invoker as Operation behavior. Now we need to implement the IServiceBehavior and we're done. Then you can directly use this behavior via the binding configuration directly using extensions. See here How to add the extended behavior in the service from configuration file.
 
But here we'll create our Custom Attribute class and will use it in the code directly as an Attribute on the service class. To create an Attribute for the service behavior we need to inherit the Attribute class in our CustomAttribute implementation with IServiceBehavior.
 
Here is the code:
  1. /// <summary>  
  2. /// Attribute class for applying custom service behavior on Service  
  3. /// </summary>  
  4. public class ExceptionHandlerLoggerBehaviorAttribute : Attribute, IServiceBehavior  
  5. {  
  6.     public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)  
  7.     {  
  8.         return;  
  9.     }  
  10.   
  11.     public void AddBindingParameters(  
  12.         ServiceDescription serviceDescription,   
  13.         ServiceHostBase serviceHostBase,   
  14.         Collection<ServiceEndpoint> endpoints,  
  15.         BindingParameterCollection bindingParameters)  
  16.     {  
  17.         return;  
  18.     }  
  19.   
  20.     public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)  
  21.     {  
  22.         foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)  
  23.         {  
  24.             foreach (OperationDescription operation in endpoint.Contract.Operations)  
  25.             {  
  26.                 IOperationBehavior behavior = new GlobalExceptionHandlerBehavior();  
  27.                 operation.Behaviors.Add(behavior);  
  28.             }  
  29.         }  
  30.     }  
  31. }  
Here we are actually applying the behavior to the end points, which in turn does the same as we do to apply a behavior via the configuration file with each EndPoint. So our Attribute class is ready, we're going to tell the Service calls that you have a custom behavior to handle the global exception.
  1. [ExceptionHandlerLoggerBehavior]  
  2. public class Service1 : IService1  
  3. {  
  4.     public string GetParseData(string value)  
  5.     {  
  6.         // check if value is alphabets/Numeric  
  7.         if (string.IsNullOrEmpty(value))  
  8.         {  
  9.             throw new ArgumentException("Method parameter value can not be null or empty");  
  10.         }  
  11.   
  12.         // split the value if it contains spaces and return first two words  
  13.         var stringArray = value.Split(' ');  
  14.   
  15.         // This will/may cause an Unhandled exception for OutOfIndex in case of single word is passed.  
  16.         return string.Format("{0}_{1}_{2} ..", stringArray[0], stringArray[1], stringArray[2]);  
  17.     }  
  18. }  
Now we'll create a client and call the service method. To create a client, simply host the service in IIS Express and find the service reference via the service reference dialog box. We'll simply use the Console application as a client.
  1. public static void Main(string[] args)  
  2. {  
  3.     ServiceReference1.Service1Client client = new Service1Client();  
  4.     try  
  5.     {  
  6.         string value = client.GetParseData("somevalue");  
  7.         Console.WriteLine(value);  
  8.     }  
  9.     catch (FaultException ex)  
  10.     {  
  11.         Console.WriteLine("========= Error ==========");  
  12.         Console.WriteLine("{0}", ex.Message);  
  13.     }  
  14.   
  15.     Console.Read();  
  16. }  
So run the client with various values. For example call the method GetParseData() as in the following:
  1. "some values are valid values" (will not throw exception)
  2. "somevalue" (will throw exception)

    IOperationInvoker2.jpg
Let's have a look at the log file. How the logs are getting produced from our custom Interceptor.
 
2013-06-24 14:09:35,339 [6] INFO  serviceLogger - Start command operation:GetParseData
2013-06-24 14:09:35,353 [6] INFO  serviceLogger - End command operation:GetParseData
2013-06-24 14:09:57,714 [6] INFO  serviceLogger - Start command operation:GetParseData
2013-06-24 14:09:57,716 [6] ERROR serviceLogger - Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at CShandler.SampleWCFServiceApplication.Service1.GetParseData(String value) in c:\Users\achoudhary\Documents\Visual Studio 2012\Projects\WpfApplication1\CShandler.SampleWCFServiceApplication\Service1.svc.cs:line 26
   at SyncInvokeGetParseData(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at CShandler.SampleWCFServiceApplication.ErrorHandlingLoggingOperationInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) in c:\Users\achoudhary\Documents\Visual Studio 2012\Projects\WpfApplication1\CShandler.SampleWCFServiceApplication\ErrorHandlingLoggingOperationInvoker.cs:line 85
 
Hope you enjoyed the article. Please leave a comment or suggestion.