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

2.SimpleMethodLogging();

3.MethodLoggingWithProxies();

4.ObjectLoggingWithProxiesFilteredOut();

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

RealProxy深入的更多相关文章

  1. .Net中的RealProxy实现AOP

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

  2. RealProxy实现AOP编程(2)

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

  3. RealProxy实现AOP编程(1)

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

  4. .Net基于RealProxy实现AOP

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

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

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

  6. .net core 2.0学习笔记(六):Remoting核心类库RealProxy迁移

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

  7. (二)远程代理Remoting/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. .htaccess下Flags速查表

    Flags是可选参数,当有多个标志同时出现时,彼此间以逗号分隔. 速查表: RewirteRule 标记 含义 描述 R Redirect 发出一个HTTP重定向 F Forbidden 禁止对URL ...

  2. Node与express开发

    1.初识Express Express 网站上是这样介绍 Express 的: "精简的.灵活的 Node.js Web 程序框架,为构建单页.多页及混合的 Web 程序提供了一系列健壮的功 ...

  3. C++中的全局变量、普通局部变量和静态局部变量的区别

    在C++中,我们经常难以说清楚全局变量.局部变量和静态局部变量的区别.本博客从变量存储特性和标识符作用域两个角度区分这三个变量. 首先,我们来看看C++程序的内存区域是如何分配的. 从上图,我们可以看 ...

  4. 通过Navicat for MySQL远程连接的时候报错mysql 1130

    1130 重装数据库 解决这个问题

  5. 核心动画与UIView的区别

    核心动画与UIView的区别 1.核心动画只作用于layer,使用核心动画之前,必须有layer 2.核心动画只是假象,并没有移动实际位置 什么时候使用核心动画,什么时候使用UIView动画 1.当不 ...

  6. 使用javaScript实现简单倒计时功能

    效果如下: <div class="warp"> <p id="txt">距离”十一“国庆放假还有:</p><br&g ...

  7. CocoaPods介绍。如何安装Ruby环境,如何下载和安装CocoaPods?

    CocoaPods介绍? 当你开发iOS应用时,会经常使用到很多第三方开源类库,比如JSONKit,AFNetWorking等等.可能某个类库又用到其他类库,所以要使用它,必须得另外下载其他类库,而其 ...

  8. app接口测试-bug分类

    前段时间在测试一个项目,任务是测试app的API.总结下遇到的问题类型: 1 通过app提交数据,隐形数据有误.(主要通过验证数据库) 比如用户通过app输入工单提交.接口数据中,用户输入的信息都正确 ...

  9. oracle问题

    (1) 连通性: 注册中心负责服务地址的注册与查找,相当于目录服务,服务提供者和消费者只在启动时与注册中心交互,注册中心不转发请求,压力较小 监控中心负责统计各服务调用次数,调用时间等,统计先在内存汇 ...

  10. windows、ubuntu下eclipse搭建java、Python环境问题总结

    前两篇博文分别讲述了如何在windows.ubuntu下用eclipse搭建java.python环境,下面就针对本人遇到的问题做一个总结. 一.windows下关于java环境变量JAVA_HOME ...