常见的AOP设计都基于Remoting的RealProxy,或者基于Emit实现的动态代理,或者基于反射的Attribute扫描拦截。但是我们还有另类的拦截方案DynamicObject,只要我们继承DynamicObject,重载几个方法即可,话不多说,上代码。
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);
}
}