1、先新建一个要被代理的类,必须实现 MarshalByRefObject
- public class User: MarshalByRefObject
- {
- public string SayHello()
- {
- Console.WriteLine("I am SayHello");
- return "I am SuperMan";
- }
- }
2、创建类 用于代理类执行方法
- ///
- /// 动态代理要执行的方法
- ///
- public class DynamicAction
- {
- ///
- /// 执行目标方法前执行
- ///
- public Action BeforeAction { get; set; }
- ///
- /// 执行目标方法后执行
- ///
- 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、创建代理工厂类
- ///
- /// 代理工厂
- ///
- ///
- public class ProxyFactory<T>
- {
- public static T Create(T obj, Dictionary<string, DynamicAction> proxyMethods = null)
- {
- var proxy = new DynamicProxy
(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
.Create(user, proxyMotheds); - t.SayHello();
- }
- }
