首先,我们先要制作一个自定义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。
5、下一章我会实现InterceptProperty这个类,其实这个类就是一个上下文属性。