您的位置:首页 > 运维架构

关于.NET AOP的实现中上下文对象的获取

2006-05-03 13:18 302 查看
       前一段时间在Wayfarer的Blog拜读了《在.Net中关于AOP的实现》,十分兴奋。但在现实使用中,还是有点遗憾,主要表现为:通过该AOP框架,虽然我们能够在业务方法利用Remoting技术,在消息传递的过程中利用监听来获取得到方法的详细信息,但无法获取的到该方法所对应的上下文对象。这也和我对Remoting不是很熟悉有关吧。
        后来查看了一下Remoting方面的东西,发现如果需要获取该上下文对象,还必须将对象通过RemotingConfiguration.RegisterWellKnownServiceType()来发布到服务器,然后可以通过Activactor.GetObject()来获取远程对象。虽然我们也可以通过透明代理对象来反射获取,并在消息截获的时候来获取得到该对象,但是这让人犯难了,耦合性太高。客户端总不可能老依赖远程对象所对应的类。
        试想一下,假设业务方法需要权限校验,并且根据权限校验的结果来进行业务处理,如果权限校验失败则执行某代码,如果成功则执行另外一些代码。那么客户端依然要依赖权限校验的类,否则怎么反射,怎么获取的到校验的结果。
        后来我又查阅了一下MSDN相关的文档,发现Dharma Shukla,Simon Fell,和 Chris Sells写了一片文章,用来解决如何共享这些上下文对象。该文章标题为《Aspect-Oriented Programming Enables Better Code Encapsulation and Reuse》,请注意该文章最后几段的描述,一下引用原文:
“…….NET provides an extensible call context that we can make use of to allow a method. For example, we can allow an object wrapped in our call-tracing aspect to have the ability to add things to the stream of trace messages by putting ourselves into the .NET context, as you can see here:
internal class CallTracingAspect : IMessageSink {
public static string ContextName {
get { return "CallTrace" ; }
}

private void Preprocess(IMessage msg) {
•••
// set us up in the call context
call.LogicalCallContext.SetData(ContextName, this);
}
•••
}
Once we've added the aspect to the call context, the method can pull us out again and participate in the tracing:
[CallTracingAttribute()]
public class TraceMe : ContextBoundObject {
public int ReturnFive(String s) {
Object obj =
CallContext.GetData(CallTracingAspect.ContextName) ;
CallTracingAspect aspect = (CallTracingAspect)obj ;
aspect.Trace("Inside MethodCall");
return 5;
}

       很幸运,我们可以通过IMethodMessage.LogicalCallContext.SetData(string,object)来将需要共享的上下文对象保存起来,客户端可以通过Object obj =System.Runtime.Remoting.Messaging.CallContext.GetData(string) 来获取所共享的上下文对象。
       因此我们可以通过设计模式来定义一个结果类,在权限校验的时候,将结果封装并保存起来,客户端获取到改结果之后再强制转换成结果类,通过结果类进行判断校验结果,从而进行其他业务处理。
这样一来,起码也解决了上下文对象无从获取的问题。也不失是一个好方发啊。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息