有人对使用 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;
}