Intercept properties with Castle Windsor IInterceptor

Does anyone have a suggestion on a better way to intercept properties with Castle DynamicProxy? In particular, I need a PropertyInfo, which I intercept, but it is not located directly on IInvocation, so I do this:

        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:

  #region IInterceptor Members

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

    }

    #endregion

Thank.

+3
source share
1 answer

This is generally not available. DynamicProxy intercepts methods (including getters and setters) and it does not care about properties.

You can optimize this code a bit by making an interceptor IOnBehalfAware(see here ) and finding that the method-> property mapping upfront.

+2
source

Source: https://habr.com/ru/post/1748197/


All Articles