.net 实现动态代理

1、先新建一个要被代理的类

public class User: MarshalByRefObject
    {
        public string SayHello()
        {
            Console.WriteLine("I am SayHello");
            return "I am SuperMan";
        }
    }

2、创建类 用于代理类执行方法 

 /// <summary>
    /// 动态代理要执行的方法
    /// </summary>
    public class DynamicAction
    {
        /// <summary>
        /// 执行目标方法前执行
        /// </summary>
        public Action BeforeAction { get; set; }
        /// <summary>
        /// 执行目标方法后执行
        /// </summary>
        public Action AfterAction { get; set; }
    }

3、创建代理类  必须继承 RealProxy类

public class DynamicProxy<T> : RealProxy
    {
        private readonly T _targetInstance = default(T);

        public Dictionary<string, DynamicAction> ProxyMethods { get; set; }
        public DynamicProxy(T targetInstance)
            : base(typeof(T))
        {
            _targetInstance = targetInstance;
        }
        public override IMessage Invoke(IMessage msg)
        {
            var reqMsg = msg as IMethodCallMessage;

            if (reqMsg == null)
            {
                return new ReturnMessage(new Exception("调用失败!"), null);
            }

            var target = _targetInstance as MarshalByRefObject;

            if (target == null)
            {
                return new ReturnMessage(new Exception("调用失败!请把目标对象 继承自 System.MarshalByRefObject"), reqMsg);
            }

            var methodName = reqMsg.MethodName;

            DynamicAction actions = null;

            if (ProxyMethods != null && ProxyMethods.ContainsKey(methodName))
            {
                actions = ProxyMethods[methodName];
            }

            if (actions != null && actions.BeforeAction != null)
            {
                actions.BeforeAction();
            }

            IMethodCallMessage callMessage = (IMethodCallMessage)msg;
            var result = RemotingServices.ExecuteMessage(target, reqMsg);

            if (actions != null && actions.AfterAction != null)
            {
                actions.AfterAction();
            }

            return result;
        }
    }

4、创建代理工厂类

/// <summary>
    /// 代理工厂
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ProxyFactory<T>
    {
        public static T Create(T obj, Dictionary<string, DynamicAction> proxyMethods = null)
        {
            var proxy = new DynamicProxy<T>(obj) { ProxyMethods = proxyMethods };

            return (T)proxy.GetTransparentProxy();
        }
    }

5、测试

class Program
    {
        static void Main(string[] args)
        {
            var proxyMotheds = new Dictionary<string, DynamicAction>();
            proxyMotheds.Add("SayHello", new DynamicAction()
            {
                BeforeAction = new Action(() => Console.WriteLine("Before Doing....")),
                AfterAction = new Action(() => Console.WriteLine("After Doing...."))
            });

            var user = new User();
            var t = ProxyFactory<User>.Create(user, proxyMotheds);
            t.SayHello();
        }
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值