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 はメソッド (ゲッターとセッターを含む) をインターセプトし、プロパティを気にしません。

IOnBehalfAwareインターセプターを作成し(こちらを参照)、事前にメソッド -> プロパティ マッピングを検出することで、このコードを少し最適化できます。

于 2010-06-02T23:17:53.127 に答える