首先,咱們先要製做一個本身定義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。