Intercept Properties With Castle Windsor IInterceptor

只愿长相守 提交于 2020-01-02 07:39:37

问题


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

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();
    }
}

Then in my IInterceptor:

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

}


回答1:


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

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



来源:https://stackoverflow.com/questions/2959812/intercept-properties-with-castle-windsor-iinterceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!