C#(AOP)方法拦截器

时间:2012-09-28 07:41:34

标签: c# function methods aop interceptor

我有很多Web服务方法,我想在一个函数中验证所有这些方法。 例如;

[Intercept]
public string Method1(POS pos, int param1, string param2)
{
    return String.Format("{0}: {1}", param1,param2);
}

[Intercept]
public int Method2(POS pos, int param3)
{
    return param3 * 2;
}

public void OnPreProcessing(...)
{
     // Before Mothod1 and Method2 called, It should enter here
     // I want to be able to cancel method execution and return another value.
     // I want to get the method name, parameter names and values         
}

现在我使用ContextBoundObject和IMessageSink来做到这一点。我可以获取方法名称,参数和值,但我无法取消方法执行并返回另一个值。我正在使用下面的东西。

public IMessage SyncProcessMessage(IMessage msg)
{
    var mcm = msg as IMethodCallMessage;
    OnPreProcessing(ref mcm);
    var retMsg = _NextSink.SyncProcessMessage(msg) as IMethodReturnMessage;
    OnPostProcessing(mcm, ref retMsg);
    return retMsg;
}

如何取消方法执行并返回其他值?

感谢。

1 个答案:

答案 0 :(得分:0)

只需放置取消检测即可忽略通话。

[Intercept]
public string Method1(POS pos, int param1, string param2)
{
    return String.Format("{0}: {1}", param1,param2);
}

[Intercept]
public int Method2(POS pos, int param3)
{
    return param3 * 2;
}

public bool OnPreProcessing(...)
{
     // Before Mothod1 and Method2 called, It should enter here
     // I want to be able to cancel method execution and return another value.
     // I want to get the method name, parameter names and values         
}

例如,如果您需要取消调用,则OnPreProcessing返回一个布尔值true。

public IMessage SyncProcessMessage(IMessage msg)
{
    var mcm = msg as IMethodCallMessage;
    var cancel = OnPreProcessing(ref mcm);
    var retMsg = cancel ? /*IMethodReturnMessage for cancelation*/ : _NextSink.SyncProcessMessage(msg) as IMethodReturnMessage;
    OnPostProcessing(mcm, ref retMsg);
    return retMsg;
}
相关问题