【发布时间】:2017-10-26 17:24:34
【问题描述】:
我想要做的是能够拦截对对象的方法和属性的调用,以解决横切关注点。我正在使用基于代理的 AOP,使用 ContextBoundObject。
但是这对于递归方法调用不起作用,对目标的第一次调用将被代理拦截并成功调用,允许我在这里做横切。但是,第一个方法中的后续方法调用将保留在目标类中,并且不会被代理拦截,就好像没有发生封送处理一样!
有什么办法可以让它工作吗? (我尽量避免使用 PostSharp、Unity 或 Spring.Net 等第三方库)
class Program
{
static void Main(string[] args)
{
var t = new SimpleObject();
t.TestMethod1();
}
}
[Intercept]
class SimpleObject : ContextBoundObject
{
public string TestMethod1()
{
return TestMethod2();
}
public string TestMethod2()
{
return "test";
}
}
[AttributeUsage(AttributeTargets.Class)]
public class InterceptAttribute : ContextAttribute, IContributeObjectSink
{
public InterceptAttribute()
: base("Intercept")
{ }
public override bool IsContextOK(Context ctx, IConstructionCallMessage ctorMsg)
{
return false;
}
public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
{
return new InterceptSink(nextSink);
}
}
public class InterceptSink : IMessageSink
{
public IMessageSink NextSink { get; private set; }
public InterceptSink(IMessageSink nextSink)
{
this.NextSink = nextSink;
}
public IMessage SyncProcessMessage(IMessage msg)
{
IMethodCallMessage mcm = (msg as IMethodCallMessage);
// { cross-cut here }
IMessage rtnMsg = this.NextSink.SyncProcessMessage(msg);
IMethodReturnMessage mrm = (rtnMsg as IMethodReturnMessage);
// { cross-cut here }
return mrm;
}
public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
return null;
}
}
【问题讨论】:
-
好奇你为什么要避免后期锐化?
-
不是我关心的问题,这是公司政策!
-
很遗憾,PostSharp 会很容易地给你这个,甚至是不需要许可证的免费方面
-
有没有人在不使用 PostSharp 的情况下找到解决方案?我现在正面临这个问题......
-
我最终使用
System.Runtime.Remoting.Proxies.RealProxy在运行时为对象创建代理。您可以在覆盖的Invoke方法中拦截方法调用。它不是纯粹的 AOP,但通过一些解决方法,您也许可以模仿 AOP
标签: c# .net marshalling aop