gpt4 book ai didi

c# - AOP Ninject 停止拦截方法被调用

转载 作者:行者123 更新时间:2023-12-02 21:49:08 25 4
gpt4 key购买 nike

我正在使用 Ninject 和 AOP 进行一些缓存。我有一个属性,我可以将其应用于我的存储库中的任何方法,并且在 BeforeInvoke 上它将返回我的缓存对象(如果有的话)并且 AfterInvoke 创建一个缓存对象。这一切都很好,但我无法弄清楚如何停止调用初始方法,即如果有缓存对象,则返回它而不是调用 intyercepted 方法。我的拦截器在这里:

public class CacheInterceptor : SimpleInterceptor
{
protected override void BeforeInvoke(IInvocation invocation)
{
Type returnType = invocation.Request.Method.ReturnType;
string cacheKey = CacheKeyBuilder.GetCacheKey(invocation, serializer);
object cachedValue = cache.Get(cacheKey);
if (cachedValue == null)
{
invocation.Proceed();
}
else
{
object returnValue = serializer.Deserialize(returnType, cachedValue);
invocation.ReturnValue = returnValue;
returnedCachedResult = true;
}
}
}

即使在 else 语句中我显然没有说要调用被调用的方法 'invocation.Proceed();'它仍然调用它。我如何告诉 ninject 只返回 invocation.ReturnValue ?

最佳答案

在这种情况下,您不能使用 SimpleInterceptor,因为它是最常见场景的基类,您希望在实际方法调用之前或之后执行操作。此外,您不得调用 Proceed 而是实现 IInterceptor 接口(interface)并将您的代码放入 Intercept 方法中。

但也许我们应该在未来的版本中扩展 SimpleInterceptor,这样您就可以防止实际方法被调用:

public abstract class SimpleInterceptor : IInterceptor
{
private bool proceedInvocation = true;

/// <summary>
/// Intercepts the specified invocation.
/// </summary>
/// <param name="invocation">The invocation to intercept.</param>
public void Intercept( IInvocation invocation )
{
BeforeInvoke( invocation );
if (proceedInvocation)
{
invocation.Proceed();
AfterInvoke( invocation );
}
}

/// <summary>
/// When called in BeforeInvoke then the invokation in not proceeded anymore.
/// Or in other words the decorated method and AfterInvoke won't be called anymore.
/// Make sure you have assigned the return value in case it is not void.
/// </summary>
protected void DontProceedInvokation()
{
this.proceedInvocation = false;
}

/// <summary>
/// Takes some action before the invocation proceeds.
/// </summary>
/// <param name="invocation">The invocation that is being intercepted.</param>
protected virtual void BeforeInvoke( IInvocation invocation )
{
}

/// <summary>
/// Takes some action after the invocation proceeds.
/// </summary>
/// <param name="invocation">The invocation that is being intercepted.</param>
protected virtual void AfterInvoke( IInvocation invocation )
{
}
}

关于c# - AOP Ninject 停止拦截方法被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com