C# 经过Attribute制做的一个消息拦截器

首先,咱们先要制做一个本身定义Attribute,让他可以具备上下文读取功能,因此咱们这个Attribute类要同一时候继承Attribute和IContextAttribute。函数

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

一、bool   IsContextOK(Context ctx, IConstructionCallMessage msg);继承

二、void  GetPropertiesForNewContext(IConstructionCallMessage msg);接口

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

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

二、GetPropertiesForNewContext 是 系统会本身主动new一个context ,而后让咱们去作些新环境应该作的事。class

    /// <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。这是这个类的实现。要解释几点:权限

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

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

三、IsContextOK方法是去推断当前是否有“Intercept”这个属性,因为咱们仅仅需要这个属性。因此仅仅要检查这个属性当前上下文有没有就能够,假设有返回true,没有的话会调用GetPropertiesForNewContext函数。

(咱们这里仅仅作拦截器功能,因此仅仅加入Intercept本身定义属性,固然假设有需要可以加入多个属性,而后在这个函数中进行对应检查)

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

相关文章
相关标签/搜索