码迷,mamicode.com
首页 > Web开发 > 详细

.Net 动态代理,AOP

时间:2016-04-28 18:17:43      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

.Net 动态代理,AOP

 

 直接上代码了。

/*****************************************
 * author:jinshuai
 * 
 * E-mail:redfox2008@126.com
 * 
 * Date:2016-04-28 
 *  
 * ***************************************/

using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;

namespace DynamicProxy.Core
{
    /// <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();
        }
    }


    /// <summary>
    /// 动态代理类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    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();
            }

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

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

            return result;
        }
    }


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


        /// <summary>
        /// 执行目标方法后执行
        /// </summary>
        public Action AfterAction { get; set; }


    }




}

 

DEMO:

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DynamicProxy.Core;

namespace DynamicProxy.Demo
{
    class Program
    {
        static void Main(string[] args)
        {

            var proxyMotheds = new Dictionary<string, DynamicAction>();

            // key is  Proxy‘s methodName, value is Actions
            proxyMotheds.Add("Add", new DynamicAction()
            {
                BeforeAction = new Action(() => Console.WriteLine("Before Doing....")),
                AfterAction = new Action(() => Console.WriteLine("After Doing...."))
            });

            var user = new User();
            //proxy for User
            var t = ProxyFactory<User>.Create(user, proxyMotheds);

            int count = 0;

            t.Add("Tom", 28, out count);

            t.SayName();

            Console.WriteLine(count);
            Console.Read();


        }
    }
}

 

 

也可以到我的Github上,直接获取完整项目   https://github.com/jinshuai/DynamicProxy.NET

 

.Net 动态代理,AOP

标签:

原文地址:http://www.cnblogs.com/red-fox/p/5443680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!