In Castle Dynamic Proxy interceptor check whether is was invoked for a specific property

780 views Asked by At

I have the following Interceptor. While it does what I intended it to do for my current use case. I found the used method a little bit hacky and was wondering if there is not a better way to do this.

public class Interceptor<TEntity, TProperty> : IInterceptor
{
    private readonly Expression<Func<TEntity, TProperty>> _propertySelector;

    public Interceptor(Expression<Func<TEntity, TProperty>> propertySelector)
    {
        _propertySelector = propertySelector;
    }

    public void Intercept(IInvocation invocation)
    {
        var invocatedMethod = invocation.Method.Name;
        var selectedMethod = (_propertySelector.Body as MemberExpression)?.Member.Name;
        if (invocatedMethod == $"set_{selectedMethod}")
        {
            //do stuff...
        }
        invocation.Proceed();
    }
}

All I need is to intercept a change on a specified property.

To be improved: - this interceptor intercepts all method and property calls, only to do stuff in a certain situation. It sound like overkill. - I need to compare two strings who are kind of alike... this sound like not the right way of doing it.

1

There are 1 answers

0
PatrickSteele On

You can use the IProxyGenerationHook to control which members get intercepted.

There's a StackOverflow question with a summary as well as this article which goes into the details of IProxyGenerationHook.