Suppose we have the following code:
public class SecurityServiceProxy
{
public string Encrypt(string input)
{
try
{
return new SecurityServiceClient().Encrypt(input);
}
catch(Exception ex)
{
//Log Exception
throw;
}
}
public string Decrypt(string input)
{
try
{
return new SecurityServiceClient().Decrypt(input);
}
catch(Exception ex)
{
//Log Exception
throw;
}
}
}
There are two duplicates in this Code. From the perspective of AOP, this repetition should be a cross-cutting concern. Therefore, it should be the best solution if it can be solved in the way of AOP, the following code implements a special form of AOP:
public class SecurityServiceProxy
{
public string Encrypt(string input)
{
return new SecurityServiceClient().ExecAndLogExcetion(client => client .Encrypt(input));
}
public string Decrypt(string input)
{
return new SecurityServiceClient().ExecAndLogExcetion(client => client .Decrypt(input));
}
}
The current Code is much simpler, mainly because the following extension methods are used:
public static class ObjectExtensions
{
public static void LockExec<T>(this T obj, Action<T> action) where T : class
{
lock (obj)
{
action(obj);
}
}
public static void ExecAndLogExcetion<T>(this T obj, Action<T> action)
{
try
{
action(obj);
}
catch (Exception)
{
//log excetion
throw;
}
}
public static void ExecAndLogExcetion<T1, T2>(this T1 obj, T2 obj1, Action<T1, T2> action)
{
try
{
action(obj, obj1);
}
catch (Exception)
{
//log excetion
throw;
}
}
public static TResult ExecAndLogExcetion<T, TResult>(this T obj, Func<T, TResult> func)
{
try
{
return func(obj);
}
catch (Exception)
{
//log excetion
throw;
}
}
public static TResult ExecAndLogExcetion<T1, T2, TResult>(this T1 obj, T2 obj1, Func<T1, T2, TResult> func)
{
try
{
return func(obj, obj1);
}
catch (Exception)
{
//log excetion
throw;
}
}
}