本文介绍了温莎城堡I拦截器的拦截特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone have a suggestion on a better way to intercept a properties with Castle DynamicProxy?

具体来说,我需要截取的PropertyInfo,但它不直接位于IInvocation上,所以我要做的是:

Specifically, I need the PropertyInfo that I'm intercepting, but it's not directly on the IInvocation, so what I do is:

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

Then in my IInterceptor:

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

}

推荐答案

通常不可用. DynamicProxy拦截方法(包括getter和setter),并且它并不关心属性.

Generally this is not available. DynamicProxy intercepts methods (incl. getters and setters), and it does not care about properties.

您可以通过使拦截器IOnBehalfAware来优化此代码(请参见此处),并发现方法->预先映射属性.

You could optimize this code a bit by making the interceptor IOnBehalfAware (see here) and discovering the method->property mapping upfront.

这篇关于温莎城堡I拦截器的拦截特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 17:25