C# 通过Attribute制作的一个消息拦截器

首先,我们先要制作一个自己定义Attribute,让他能够具有上下文读取功能,所以我们这个Attribute类要同一时候继承Attribute和IContextAttribute。

接口IContextAttribute中有两个方法须要实现

1、bool   IsContextOK(Context ctx, IConstructionCallMessage msg);

2、void  GetPropertiesForNewContext(IConstructionCallMessage msg);

简单解释一下这两个方法:

1、IsContextOK方法是让我们检查当前上下文(current  context)是否有问题,假设没有问题返回true。有问题的话返回false。然后该类会去调用GetPropertiesForNewContext

2、GetPropertiesForNewContext 是 系统会自己主动new一个context ,然后让我们去做些新环境应该做的事。

    /// <summary>
    /// Some class if you want to intercept,you must mark this attribute.
    /// </summary>
    public class InterceptAttribute : Attribute, IContextAttribute
    {
        public InterceptAttribute()
        {
            Console.WriteLine(" Call 'InterceptAttribute' - 'Constructor'  ");
        }
        public void GetPropertiesForNewContext(IConstructionCallMessage ctorMsg)
        {
            ctorMsg.ContextProperties.Add(new InterceptProperty());
        }
        public bool IsContextOK(Context ctx, IConstructionCallMessage ctorMsg)
        {
            InterceptProperty interceptObject = ctx.GetProperty("Intercept") as InterceptProperty;
            
            return interceptObject != null;
        }
    }

ok。这是这个类的实现。要解释几点:

1、InterceptAttribute这个类继承的是Attribute。用于[Attribute]标记用的。

2、InterceptAttribute这个类继承IContextAttribute,用于给标记上的类获得上下文权限,然后要实现该接口的两个方法。

3、IsContextOK方法是去推断当前是否有“Intercept”这个属性,由于我们仅仅须要这个属性。所以仅仅要检查这个属性当前上下文有没有就可以,假设有返回true,没有的话会调用GetPropertiesForNewContext函数。

(我们这里仅仅做拦截器功能,所以仅仅加入Intercept自己定义属性,当然假设有须要能够加入多个属性,然后在这个函数中进行对应检查)

4、假设调用GetPropertiesForNewContext函数。他会让我们进行新上下文环境的自己定义,我在这做了一个操作:在当前的上下文中加入一个属性,这个属性就是Intercept。

原文地址:https://www.cnblogs.com/brucehome/p/6060859.html