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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM