我的一个自己写的更新缓存的aop实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Contexts;

namespace AopDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var tst = new test();
            tst.show();
            tst.show2();
            Console.ReadLine();
        }
    }
    [AutoClearCache("CacheName")]
    public class test : ContextBoundObject
    {
        [AutoClearCacheMethod]
        public void show()
        {
            Console.WriteLine("调用本方法");
        }

        public void show2()
        {
            Console.WriteLine("调用方法2");
        }
    }

    public sealed class AutoClearCacheAop : IMessageSink
    {
        private IMessageSink nextSink; //保存下一个接收器

        public AutoClearCacheAop(IMessageSink nextSink, string CacheName)
        {
            this.CacheName = CacheName;
            this.nextSink = nextSink;
        }
        ///  IMessageSink接口方法,用于异步处理,我们不实现异步处理,所以简单返回null,
        ///  不管是同步还是异步,这个方法都需要定义
        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            return null;
        }
        /// 下一个接收器
        public IMessageSink NextSink
        {
            get { return nextSink; }
        }
        public IMessage SyncProcessMessage(IMessage msg)
        {
            IMessage retMsg = null;

            IMethodCallMessage call = msg as IMethodCallMessage;

            if (call == null || (Attribute.GetCustomAttribute(call.MethodBase, typeof(AutoClearCacheMethodAttribute))) == null)
                retMsg = nextSink.SyncProcessMessage(msg);
            else
            {
                Console.WriteLine(this.CacheName);
                //传递消息给下一个接收器 - > 就是指执行你自己的方法
                retMsg = nextSink.SyncProcessMessage(msg);
                Console.WriteLine("拦截方法完");
            }

            return retMsg;
        }
        private string CacheName;
    }
    /// <summary>
    /// 标注类某方法内所有数据库操作加入事务控制
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public sealed class AutoClearCacheAttribute : ContextAttribute, IContributeObjectSink
    {
        private string CacheName;
        /// <summary>
        /// 标注类某方法内所有数据库操作加入事务控制,请使用TransactionMethodAttribute同时标注
        /// </summary>
        public AutoClearCacheAttribute(string CacheName)
            : base(CacheName)
        {
            this.CacheName = CacheName;
        }

        public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink next)
        {
            return new AutoClearCacheAop(next, this.CacheName);
        }
    }

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public sealed class AutoClearCacheMethodAttribute : Attribute
    {
        
    }


}

posted @ 2013-04-25 15:21  qisheng722  阅读(315)  评论(0编辑  收藏  举报