4

有人对使用 Castle DynamicProxy 拦截属性的更好方法有建议吗?

具体来说,我需要我正在拦截的 PropertyInfo,但它不是直接在 IInvocation 上,所以我要做的是:

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 中:

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

}

4

1 回答 1

4

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

IOnBehalfAware您可以通过制作拦截器(参见此处)并预先发现方法-> 属性映射来稍微优化此代码。

于 2010-06-02T23:17:53.127 回答