请参阅开源项目NConcern .NET AOP Framework 。
例子
你的静态类
static public class Calculator
{
static public int Add(int a, int b)
{
return a + b;
}
}
记录器
static public class Logger
{
static public void Log(MethodInfo method, object[] arguments, Exception exception)
{
Console.WriteLine("{0}({1}) exception = {2}", method.Name, string.Join(", ", arguments), exception.Message);
}
}
看点:登录异常
public class Logging : IAspect
{
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
yield return Advice.Basic.After.Throwing((instance, arguments, exception) =>
{
Logger.Log(method, arguments, exception);
});
}
}
Joinpoint : 计算器的方法
var calculatorMethods = new Func<MethodInfo, bool>(method => method.ReflectedType == typeof(Calculator));
激活连接点的日志记录方面
Aspect.Weave<Logging>(calculatorMethods);