Alternative AOP design, alternative aop
Common AOP designs are based on Remoting RealProxy, Emit-based Dynamic proxy, or reflection-based Attribute scan interception. However, we also have an alternative Interception Scheme DynamicObject. As long as we inherit DynamicObject and overload several methods, let's not talk about it. Let's talk about the code.
public class DynamicProxy<T>:DynamicObject where T:class{ private T _source; public DynamicProxy(T source){if(source==null){throw new ArgumentNullException("source");}_source=source;} public override bool TryInvokeMember(InvokeMemberBinder binder,object[] args,out object result) { Func<MethodInfo,bool> func=m=>{//filter logic code}; var method=_source.GetType().GetMethods().FirstOrDefault(func); if(method!=null&&!method.IsAbstract) { //MethodBeginInvokeHander?.Invoke(_source,args); result=method.Invoke(_source,args); //MethodEndInvokeHander?.Invoke(_source,args); return true; } result=null; return false; }}
Demo:
public class T{ public string GetName(string name){return name;}}class Program{ static void Main(string[] args) { Dynamic<T> proxy=new Dynamic<T>(new T()); proxy.MethodBeginInvokeHandler+=MethodBeginInvoke; proxy.MethodEndInvokeHandler+=MethodEndInvoke; dynamic d=proxy; d.GetName("xxx"); } static void MethodBeginInvoke(object sender,MethodEventArgs e) { Console.WriteLine("Start Invoke:"+e.Name); } static void MethodEndInvoke(object sender,MethodEventArgs e) { Console.WriteLine("Result:"+e.Result); }}