RealProxy深入

时间:2022-10-30 20:30:42

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            NoMethodLogging();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
            SimpleMethodLogging();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
            MethodLoggingWithProxies();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
            ObjectLoggingWithProxiesFilteredOut();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
            ObjectLoggingWithProxiesFilteredIn();
            Console.ReadLine();
        }

        private static void NoMethodLogging()
        {
            Console.WriteLine("Start - No method logging...");
            IRepository<Order> orderRepository = new Repository<Order>();
            Order order = , CustomerId = , Number = " };
            orderRepository.Add(order);
            orderRepository.Update(order);
            orderRepository.Delete(order);
            Console.WriteLine("End - No method logging...");
        }

        private static void SimpleMethodLogging()
        {
            //用SimpleMethodLoggingRepository,把Repository包装一下后,使用。
            Console.WriteLine("Start - Simple method logging...");
            IRepository<Order> orderRepository = new SimpleMethodLoggingRepository<Order>(new Repository<Order>());
            Order order = , CustomerId = , Number = " };
            orderRepository.Add(order);
            orderRepository.Update(order);
            orderRepository.Delete(order);
            Console.WriteLine("End - Simple method logging...");
        }

        private static void MethodLoggingWithProxies()
        {
            Console.WriteLine("Start - RealProxy method logging...");
            IRepository<Order> orderRepository = RealProxyMethodLoggingFactory.Create<Order>();
            Order order = , CustomerId = , Number = " };
            orderRepository.Add(order);
            orderRepository.Update(order);
            orderRepository.Delete(order);
            Console.WriteLine("End - RealProxy method logging...");
        }

        private static void ObjectLoggingWithProxiesFilteredOut()
        {
            Console.WriteLine("Start - RealProxy object logging...");
            IRepository<NotOrder> orderRepository = RealProxyObjectLoggingFactory.Create<NotOrder>();
            NotOrder order = , CustomerId = , Number = " };
            orderRepository.Add(order);
            orderRepository.Update(order);
            orderRepository.Delete(order);
            Console.WriteLine("End - RealProxy object logging...");
        }

        private static void ObjectLoggingWithProxiesFilteredIn()
        {
            Console.WriteLine("Start - RealProxy object logging...");
            IRepository<Order> orderRepository = RealProxyObjectLoggingFactory.Create<Order>();
            Order order = , CustomerId = , Number = " };
            orderRepository.Add(order);

            order.Number += "-Changed";
            orderRepository.Update(order);
            orderRepository.Delete(order);
            Console.WriteLine("End - RealProxy object logging...");
        }
    }

Entities.(NotOrder.cs/Order.cs)

 public class NotOrder
    {
        public int CustomerId { get; set; }

        public int Id { get; set; }

        public string Number { get; set; }
    }

public class Order
    {
        public int CustomerId { get; set; }

        public int Id { get; set; }

        public string Number { get; set; }
    }

Interfaces.IRepository.cs

internal interface IRepository<T>
    {
        void Add(T entity);

        void Delete(T entity);

        void Update(T entity);
    }

Implementations.Repository.cs

  public class Repository<T> : IRepository<T>
    {
        public void Add(T entity)
        {
            Console.WriteLine("Adding {0}", entity);
        }

        public void Delete(T entity)
        {
            Console.WriteLine("Deleting {0}", entity);
        }

        public void Update(T entity)
        {
            Console.WriteLine("Updating {0}", entity);
        }
    }

Proxies.MethodProxy.cs

internal class MethodProxy<T> : RealProxy
    {
        private readonly T decorated;

        public MethodProxy(T decorated)
            : base(typeof(T))
        {
            this.decorated = decorated;
        }

        public override IMessage Invoke(IMessage msg)
        {
            var methodCall = msg as IMethodCallMessage;
            OnBeforeExecute(methodCall);
            try
            {
                var methodInfo = methodCall.MethodBase as MethodInfo;
                var result = methodInfo.Invoke(decorated, methodCall.InArgs);
                OnAfterExecute(methodCall);
                , null, methodCall);
            }
            catch(Exception ex)
            {
                OnErrorExecute(methodCall);
                return new ReturnMessage(ex, methodCall);
            }
        }

        public event EventHandler<IMethodCallMessage> AfterExecute;

        public event EventHandler<IMethodCallMessage> BeforeExecute;

        public event EventHandler<IMethodCallMessage> ErrorExecute;

        private void OnAfterExecute(IMethodCallMessage methodCall)
        {
            if(AfterExecute!=null)
            {
                AfterExecute(this, methodCall);
            }
        }

        private void OnBeforeExecute(IMethodCallMessage methodCall)
        {
            if (BeforeExecute != null)
            {
                BeforeExecute(this, methodCall);
            }
        }

        private void OnErrorExecute(IMethodCallMessage methodCall)
        {
            if (ErrorExecute != null)
            {
                ErrorExecute(this, methodCall);
            }
        }
    }

Proxies.ObjectProxy.cs

internal class ObjectProxy<T> : RealProxy
    {
        private readonly T decorated;
        private Func<object[], bool> filter;

        public ObjectProxy(T decorated) : base(typeof(T))
        {
            this.decorated = decorated;
            filter = x => true;
        }

        public Func<object[], bool> Filter
        {
            get { return filter; }
            set
            {
                if (value == null)
                    filter = x => true;
                else
                    filter = value;
            }
        }

        public override IMessage Invoke(IMessage msg)
        {
            var methodCall = msg as IMethodCallMessage;
            if (filter(methodCall.InArgs)) OnBeforeExecute(methodCall);
            try
            {
                var methodInfo = methodCall.MethodBase as MethodInfo;
                var result = methodInfo.Invoke(decorated, methodCall.InArgs);
                if (filter(methodCall.InArgs)) OnAfterExecute(methodCall);
                , null, methodCall);
            }
            catch (Exception ex)
            {
                if (filter(methodCall.InArgs)) OnErrorExecute(methodCall);
                return new ReturnMessage(ex, methodCall);
            }
        }

        public event EventHandler<IMethodCallMessage> AfterExecute;

        public event EventHandler<IMethodCallMessage> BeforeExecute;

        public event EventHandler<IMethodCallMessage> ErrorExecute;

        private void OnAfterExecute(IMethodCallMessage methodCall)
        {
            if (AfterExecute != null)
            {
                AfterExecute(this, methodCall);
            }
        }

        private void OnBeforeExecute(IMethodCallMessage methodCall)
        {
            if (BeforeExecute != null)
            {
                BeforeExecute(this, methodCall);
            }
        }

        private void OnErrorExecute(IMethodCallMessage methodCall)
        {
            if (ErrorExecute != null)
            {
                ErrorExecute(this, methodCall);
            }
        }
    }

最简单的日志添加方法,装饰者模式!

Implementations.SimpleMethodLoggingRepository.cs

internal class SimpleMethodLoggingRepository<T> : IRepository<T>
    {
        private readonly IRepository<T> decorated;

        public SimpleMethodLoggingRepository(IRepository<T> decorated)
        {
            this.decorated = decorated;
        }

        public void Add(T entity)
        {
            Log("Simple decorator - Before Adding {0}", entity);
            this.decorated.Add(entity);
            Log("Simple decorator - After Adding {0}", entity);
        }

        public void Delete(T entity)
        {
            Log("Simple decorator - Before Deleting {0}", entity);
            this.decorated.Delete(entity);
            Log("Simple decorator - After Deleting {0}", entity);
        }

        public void Update(T entity)
        {
            Log("Simple decorator - Before Updating {0}", entity);
            this.decorated.Add(entity);
            Log("Simple decorator - After Updating {0}", entity);
        }

        private void Log(string message,object arg)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(message, arg);
            Console.ResetColor();
        }
    }

使用RealProxy实现日志添加!

Implementations.RealProxyMethodLoggingFactory.cs

  internal class RealProxyMethodLoggingFactory
    {
        public static IRepository<T> Create<T>()
        {
            var methodProxy = new MethodProxy<IRepository<T>>(new Repository<T>());
            methodProxy.BeforeExecute += MethodProxy_BeforeExecute;
            methodProxy.AfterExecute += MethodProxy_AfterExecute;
            methodProxy.ErrorExecute += MethodProxy_ErrorExecute;
            return methodProxy.GetTransparentProxy() as IRepository<T>;
        }

        private static void Log(string message,object arg)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(message, arg);
            Console.ResetColor();
        }

        private static void MethodProxy_ErrorExecute(object sender, IMethodCallMessage e)
        {
            Log("RealProxy - Error executing '{0}'", e.MethodName);
        }

        private static void MethodProxy_AfterExecute(object sender, IMethodCallMessage e)
        {
            Log("RealProxy - After executing '{0}'", e.MethodName);
        }

        private static void MethodProxy_BeforeExecute(object sender, IMethodCallMessage e)
        {
            Log("RealProxy - Before executing '{0}'", e.MethodName);
        }
    }

使用RealProxy实现日志添加,并添加过滤!

Implementations.RealProxyObjectLoggingFactory.cs

internal class RealProxyObjectLoggingFactory
    {
        public static IRepository<T> Create<T>()
        {
            var objectProxy = new ObjectProxy<IRepository<T>>(new Repository<T>());
            objectProxy.BeforeExecute += objectProxy_BeforeExecute;
            objectProxy.AfterExecute += objectProxy_AfterExecute;
            objectProxy.ErrorExecute += objectProxy_ErrorExecute;
            objectProxy.Filter = x =>
            {
                ) ] is Order;
                return false;
            };
            return objectProxy.GetTransparentProxy() as IRepository<T>;
        }

        private static void Log(string message, object arg = null)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(message);
            Console.ResetColor();
        }

        private static void objectProxy_AfterExecute(object sender, IMethodCallMessage e)
        {
            Log(] as Order), "Order")));
        }

        private static void objectProxy_BeforeExecute(object sender, System.Runtime.Remoting.Messaging.IMethodCallMessage e)
        {
            Log(] as Order), "Order")));
        }

        private static void objectProxy_ErrorExecute(object sender, IMethodCallMessage e)
        {
            Log(] as Order), "Order")));
        }
    }

结果图:

1.NoMethodLogging();

RealProxy深入

2.SimpleMethodLogging();

RealProxy深入

3.MethodLoggingWithProxies();

RealProxy深入

4.ObjectLoggingWithProxiesFilteredOut();

RealProxy深入

5.ObjectLoggingWithProxiesFilteredIn();  (只截取了部分图片,引用了ObjectDumper.dll才出现这样的显示方式)

RealProxy深入

RealProxy深入的更多相关文章

  1. &period;Net中的RealProxy实现AOP

    序言 这个AOP要从我们公司的一个事故说起,前段时间公司的系统突然在乌云中出现,数据被泄露的一览无余,乌云上显示是SQL注入攻击.呵,多么贴近生活的一个露洞,可谓是人尽皆知啊.然而却华丽丽的给拉我们一 ...

  2. RealProxy实现AOP编程&lpar;2&rpar;

    稍微变化一下!注意区别. Program.cs class Program { static void Main(string[] args) { User user = " }; var ...

  3. RealProxy实现AOP编程&lpar;1&rpar;

    Program.cs class Program { static void Main(string[] args) { User user = " }; var processor = T ...

  4. &period;Net基于RealProxy实现AOP

    一.概述 关于AOP(面向切面编程)还是先讲一个日常经常碰到的场景"错误日志的记录",一般来说我们编码的时候想记录错误日志都是用try..catch来进行捕捉和记录,慢慢的你会发现 ...

  5. 真实代理(RealProxy)在WCF中的运用

    在WCF中,当我们在调用服务端的方法时,一般有两点需要考虑:1.捕获服务端的异常信息,记录日志:2.及时关闭会话信道,当调用超时或调用失败时及时中断会话信道.我们一般会像下面这样处理(以Calcula ...

  6. &period;net core 2&period;0学习笔记(六):Remoting核心类库RealProxy迁移

    在学习.net core的过程中,我们已经明确被告知,Remoting将不会被支持.官方的解释是,.net framework 类型包含了太多的Runtime的内容,是一个非常重量级的服务实现,已被确 ...

  7. (二)远程代理Remoting&sol;RealProxy

    使用.Net Remoting/RealProxy 采用TransparentProxy和RealProxy实现对象的代理,实现思路如下:Client -TransparentProxy - Real ...

  8. RealProxy AOP的实现

    微软有一篇实现 一下是对于该实现的理解 https://msdn.microsoft.com/zh-cn/library/dn574804.aspx public class DynamicProxy ...

  9. RealProxy AOP过滤方法的参数

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...

随机推荐

  1. Android驱动开发前的准备

    最近看了一些Android驱动开发前需要知道的资料,收获很多,接下来就谈谈我自己的一些心得体会. Android在近几年时间发展迅速,已经成为智能手机操作系统的老大.不过,因为Android原生的代码 ...

  2. UnsupportedClassVersionError 错误解决办法

    偶然遇到关于版本问题的错误,为了以后查找方便记录下来.有更好的办法欢迎大家更正. 错误内容: Exception in thread "main" java.lang.Unsupp ...

  3. Thinkphp框架 -- ajax无刷新上传图片

    用Thinkphp框架做无刷新上传图片 视图层 View <!doctype html> <html lang="en"> <head> &lt ...

  4. Spring&lpar;一&rpar;简述(转载)

    原文出自:http://www.cnblogs.com/liunanjava/p/4396794.html 一.Spring简述 Spring是一个开源框架,Spring是于2003 年兴起的一个轻量 ...

  5. 使用命令行将Excel数据表导入Mysql中的方法小结

    从Excel数据表导入MySQL,已经做过好几次了,但每次都会碰到各种问题:invalid utf8 character string, data too long, ...,浪费了不少时间 为了提高 ...

  6. IOS 警告框 &lpar;UIAlertView&rpar;的使用方法

    1.普通警告框 IOS的SDK中提供了一个方便的类库UIAlertView,配合着不同参数来使用此类可以做出大多数的警告框,如下代码是IOS最简单的警告框. UIAlertView *alert = ...

  7. C嵌入汇编

    概述:linux内核源码中,有很多C语言中嵌入了汇编语句,如何理解这些汇编语句,对理解内核有很重要的作用. 具有输入和输出参数的嵌入式汇编语句的基本格式为: asm("汇编语句" ...

  8. HK2框架的简单自实现kunJ

    kunJ kunJ框架,是基于HK2框架的一个自实现注入框架,功能比较简单,重在探索依赖注入的实现原理. 实现细节 自定义3个注解,Access,Inject,Service 在Service中实现对 ...

  9. Vue源码后记-其余内置指令(2)

    -- 指令这个讲起来还有点复杂,先把html弄上来: <body> <div id='app'> <div v-if="vIfIter" v-bind ...

  10. MySQL的启动程序

    1.mysqld:             mysql server [root@test bin]# ./mysqld --user=mysql & [root@test bin]# ps ...