Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern / C# trick for repeated bit of code

I have a WCF service which logs any exceptions and then throws them as FaultExceptions.

I am doing a lot of repetition e.g. in each service method.

try { 
   // do some work

}
catch(Exception ex)
{
  Logger.log(ex);

  // actually will be Fault Exception but you get the idea.
  throw ex;
}

I am looking for a more elegant way to do this as I am cutting and pasting the try/catch throughout each service.

Is there a design pattern /C# trick that could be used to make this more elegant?

like image 560
AJM Avatar asked Mar 04 '13 14:03

AJM


People also ask

What Is design pattern C?

Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects. The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns.

Are there design patterns in C?

Yes, there are. Lazy initialization, singleton, object pool, object state etc.


1 Answers

You're talking about AOP - Aspect Oriented Programming

Here's how I do it by passing the "work" as a lambda:

public partial static class Aspect
{
  public static T HandleFaultException<T>( Func<T> fn )
  {
    try
    { 
      return fn();
    }
    catch( FaultException ex )
    {
      Logger.log(ex);
      throw;
    }
  }
}

Then to use it:

return Aspect.HandleFaultException( () =>
  {
    // call WCF
  }
);

There are other ways to achieve the same goal, and even some commercial products, but I find this way to be the most explicit and flexible.

For example, you can write an aspect that creates and disposes the client for you:

public partial static class Aspect
{
  public static T CallClient<T>( Func<Client, T> fn )
  {
    using ( var client = ... create client ... )
    {
      return fn( client );
    }
  }
}

and so:

return Aspect.CallClient( client =>
  {
    return client.Method( ... );
  }
);

And then, you can wrap all the aspects you normally want to apply and create one master aspect.

like image 147
Nick Butler Avatar answered Oct 26 '22 21:10

Nick Butler