Alternative AOP design, alternative aop

Source: Internet
Author: User

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);    }}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.