C#制作一个消息拦截器(intercept)2

好了,接着上一篇文章,我们要实现一个InterceptProperty类。

先讲一下,这个类我们要继承两个接口IContextProperty和IContributeObjectSink

IContextProperty:这个接口是说明该类是一个上下文属性,他其中有两个方法IsNewContextOK和Freeze

1、Freeze()该方法用来定位被创建的Context的最后位置,一般不用写入什么逻辑。

2、IsNewContextOK()这个方法让我们检验:我们对当前新Context是否满意。满意返回true,不满意false则会异常,我们再进行处理。

IContributeObjectSink: 这个接口是是一个消息池,只有继承这个接口我们才能接收Object消息。

当然也有IContributeEnvoySink,IContributeClientContextSink,IContributeServerContextSink,这些消息池,能接收不同形式的消息,在这里不过多解释。

1、IContributeObjectSink 里面的 GetObjectSink()方法需要我们去实现,主要作用是得到一个消息池的对象。


好,话不多说,直接贴代码:

//IContributeObjectSink,IContributeEnvoySink,IContributeClientContextSink,IContributeServerContextSink
    public class InterceptProperty:IContextProperty,IContributeObjectSink
    {
        public InterceptProperty()
        {
            Console.WriteLine(" Call 'InterceptProperty' - 'Constructor'  ");
        }
        public string Name { 
            get
            {
                return "Intercept";
            }
        }
        public void Freeze(Context newContext)
        {

        }
        public bool IsNewContextOK(Context newCtx)
        {
            var result = newCtx.GetProperty("Intercept");
            return result!=null;
            //return false;
        }

        public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
        {
            InterceptSink interceptSink = new InterceptSink(nextSink);
            return interceptSink;
        }
    }
简单解释一下,IsNewContextOK() 函数中,我主要是在当前新的上下文中获得我想要的Intercept属性,正常情况下,系统会构造出InterceptProperty对象,GetProperty()函数就是get出Name属性是否匹配,如果匹配则return true,否则异常。
另外的GetObjectSink方法则是得到一个InterceptSink的对象,下一节我会实现InterceptSink类。

猜你喜欢

转载自blog.csdn.net/lwcbest/article/details/38122857
今日推荐