Yesterday I published a post showing how we can use AOP and Castle Dynamic Proxy to get automatic change notification for ViewModels by intercepting property setters. One of the comments I got was from Krzysztof Koźmic who suggested that I should use ProxyGenerationHook to narrow down the scope of the proxy.
By implementing the IProxyGenerationHook we get to choose which methods to intercept. In my original implementation this logic was handled by the interceptor itself. The interceptor would check that the method being intercepted was indeed a property setter, that it was not of type ICommand, and that it was not marked for exclusion. By implementing a ProxyGenerationHook I could move all this code into a separate class, making my interceptor much cleaner. The ShouldInterceptMethod implementation of the ProxyGenerationHook now looks like this:
I also got a good question from Anders Knutsen asking how to handle change notification for properties depending on another property. A typical scenario for a ViewModel might be to have a ZipCode-property with both setter and getter, and City and State properties with only getters. When you set the ZipCode you raise change notification for ZipCode, City and State. In the City- and State-getter you look up the values based on the ZipCode. This means that you must be able to raise multiple change notifications in a single setter.
I solved this by adding a new NotifyChangesFor-attribute that you can decorate properties with to trigger change notification for additional dependent properties.
I have also updated the tests to document this behavior.
The sample code has been updated with the new ProxyGenerationHook and the new NotifyChangesFor-attribute.