2010-06-02 123 views
3

有没有人有更好的方法来拦截与Castle DynamicProxy属性的建议?比较特别的,我需要的是我截取的PropertyInfo,但它不是直接在IInvocation,所以我要做的就是:截取属性与城堡温莎IInterceptor

 public static PropertyInfo GetProperty(this MethodInfo method) 
    { 
     bool takesArg = method.GetParameters().Length == 1; 
     bool hasReturn = method.ReturnType != typeof(void); 
     if (takesArg == hasReturn) return null; 
     if (takesArg) 
     { 
      return method.DeclaringType.GetProperties() 
       .Where(prop => prop.GetSetMethod() == method).FirstOrDefault(); 
     } 
     else 
     { 
      return method.DeclaringType.GetProperties() 
       .Where(prop => prop.GetGetMethod() == method).FirstOrDefault(); 
     } 
    } 

然后在我的IInterceptor:

#region IInterceptor Members 

    public void Intercept(IInvocation invocation) 
    { 
     bool doSomething =         invocation.Method.GetProperty().GetCustomAttributes(true).OfType<SomeAttribute>().Count() > 0; 

    } 

    #endregion 

感谢。

回答

2

通常这不可用。 DynamicProxy拦截方法(包括getters和setter),它不关心属性。

您可以通过制作拦截器IOnBehalfAware(请参阅here)并发现方法 - >属性映射的前沿来稍微优化此代码。