Alex Hope O'Connor
Alex Hope O'Connor

Reputation: 9704

Inject/handle property getters/setters?

I have written an abstract class that I am using to automate a lot of INotifyPropertyChanged and IDataErrorInfo stuff. However this requires that I specify a custom getter/setter which calls a custom method for every property.

To avoid the extra typing I have been trying to find a way to override/handle the property getters/setters in an object and call the custom method instead of the generated getter/setter.

I tried inheriting from DynamicObject and overriding TryGetMember and TrySetMember, however these methods only seem to work if the object is declared as dynamic.

So I want to know if what I am trying to achieve is possible at all through .NET reflection or some other mechanism, also is there anyway to detect if the property setter/getter has been defined in code?

Thanks, Alex.

Upvotes: 2

Views: 987

Answers (1)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

You can get information about properties of a type using Type.GetProperties method. You will receive a collection of PropertyInfo object. Those object have CanRead and CanWrite properties which say if properties are readable/writable.

To override this behavior you would have to:

  1. Create dynamic proxy generator
  2. Dynamic proxies should intercept calls to methods in form of get_PropA and set_PropA, which are effectively getters and setters, where you can add your additional logic
  3. Instead of using constructors in code to create those objects, use your proxy generator which will create the object and then wrap it inside a proxy.
  4. Naturally, your classes must not be sealed, and properties must be virtual in order to create proxy

For free solutions you are best to use Castle DynamicProxy. If you are ready to spend some money, take a look at PostSharp which already implements many things of similar nature. Like INotifyProperty chage, undo/redo etc. You could also take a look at any AOP framework which supports aspect weaving, but DynamicProxy would be my pick for situation you described.

Upvotes: 3

Related Questions