2013-09-25 37 views
2

我正在使用Ninject和AOP来做一些缓存。我有一个属性,我可以应用于我的存储库中的任何方法和BeforeInvoke它将返回我的缓存的对象,如果有一个和AfterInvoke创建一个缓存的对象。这一切都很好,但我不知道如何停止初始方法被调用,即如果有缓存对象的返回,而不是调用intycecepted方法。我的拦截器是在这里:AOP Ninject停止拦截被调用的方法

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?

+0

你肯定你的拦截器被称为?你能在调试器中完成它吗? –

+0

是拦截器被调用,我可以看到invocation.ReturnValue = returnValue;正在设定,但它也称为方法 – Joshy

回答

5

在这种情况下,您不能使用SimpleInterceptor,因为这意味着您需要在实际方法调用之前或之后执行操作的最常见场景的基类。您也不允许拨打Proceed而是实施IInterceptor接口,并将您的代码放入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) 
    { 
    } 
} 
+0

辉煌,谢谢! – Joshy