2009年6月9日星期二

关于动态调用路由(Dynamic Calling Routing)

今天早上在思考关于Transaction Scope的问题的时候~突然发现了一个一种很特别的方法可以实现动态的调用路由。
简单的说就是这样的:无论是C & C++  的Function Pointer 也好,还是Java,C# 的 Delegate 也好~都是一种静态的调用路由,即针对同一个FP或者Delegate,无论在任何时候去调用它,最后都是同一个方法或者函数被Invoke。
当然对于Delegate来说,其具有Multicast的特性,也就是说调用一个Delegate可能会有一组签名相同的方法被调用~
但是不管怎么讲,这种调用都还是静态的(虽然可以利用Delegate的Multicast方式来模拟动态路由,不过这里不讨论这个问题)。
那我们是否有可能让一个Delegate在不同的Context中具有完全不同的行为呢~即在不同的上下文中同一个Delegate将I动态的nvoke不同的方法~

举个例子解释这种 Scenario:
public interface IContract
{
    string PrcoessString(string a,string b);
}

public class Contact : IContract
{
    public string PrcoessString(string a ,string b)
    {
         return a+b;
    }
}

public class Remove : IContract
{
   public string ProcessString(string a, string b)
   {
       return a.Replace(b,string.Empty);
   }
}

public delegate string ProcessStringDelegate(string a, string b);

Remove和Contact两个类中都实现了IContract中定义的方法,具有完全相同的方法签名,但是却有不同的行为。我在考虑是否有中办法让同一个ProcessStringDelegate实例,在上下文A中出发Contact中的方法,而在上下文B中触发Remove中的方法。
初步的想法就是实现一个MethodCallRoute类,在里面定义两个ProcessStringDelegate实例,分别指向Contact和Remove中的方法,这两个Delegate都是静态的。然后在MethodCallRoute类也实现接口IContract,然后在其实现的ProcessString方法中判断上下文,然后决定调用哪个静态的Delegate~
从而MethodCallRoute类中的ProcessString方法的Delegate就是一个Dynamic Call Router

关于上下文的判断,可以使用自定义的方式:
1.维护一个static 的栈
2.进入一个上下文的时候往栈中Push一个上下文对象,推出上下文时Pop~
这样栈顶的元素必然就是当前上下文~
在C#中可以实现一个Context类,该类:
1.在构造函数中把自己压入上下文栈
2.实现IDisposable接口,并在Dispose方法中检查栈顶元素是否为自己,是则弹栈。
3.使用using语句描述上下文范围,保证进入上下文的时候Context对象被构造,离开上下文的时候对象被Dispose~
详细可以看我的CodePlex上的项目Windy Foundation Library(http://windyfoundationlib.codeplex.com/) 中Windy工程Context命名空间下的Context类的实现(http://windyfoundationlib.codeplex.com/SourceControl/changeset/view/23183#441624

另外还有一个简单的办法就是通过反射去Track调用的函数,找到Call Site以后获取其MethodBaseInfo,然后更具其方法的名字等去决定上下文,亦或是获取这个Method相关的Attribute来决定路由。

TimNew
------------
Release you passion
To Realize you potential
---------------------------------
Tip Of the Day:
Mark Twain  - "The human race has one really effective weapon, and that is laughter."

Posted via email from timnew's posterous

没有评论:

发表评论