IDataErrorInfo Behavior Using DynamicProxy
Castle Windsor sample application now supports interface. If you have read my post on how to implement INotifyPropertyChanged interface using Castle DynamicProxy, here same technique is used in parallel with Fluent Validation framework for Silverlight. The magic behind this approach is that your models are clear as you want them to be. Let’s see in more detail how this can be done.
A typical implementation of interface is like the following, where you need to specify two things when object state has errors: A. Using the indexer you specify if a property value on the object has any error B. Error property that returns a general error message when object has any errors.
Let’s see how this looks on our simple Customer object:
As you can see, our once clean object, is cluttered. One reason is that the validation logic is inside the same class (SoC anyone?), but even if we remove that, we’d have the interface implementation that delegate the dirty work to a validator, but again the noise is still there.
The solution is to use DataErrorInfoBehavior. Using this approach you don’t even need to implement the interface on your model class and it will be done for you dynamically. All you need to do is to register and resolve your objects from the container, and let it do all the heavy lifting for you.
To make the models resolved from the container implement interface for you, first you need to specify the additional interface that you require, and then add an interceptor to implement that interface dynamically. The following snippet will register your Customer class along with necessary interface and interceptor:
public class ModelInstaller : IWindsorInstaller
All the magic is in the DataErrorInfoBehavior class. Here we’ll validate the object based on what method of the is being called and set the return value of that method:
public void Intercept(IInvocation invocation)
If you resolve an instance of your object from the container and bind it to a view, you’ll see that this is working pretty sweet.
If you are interested, you can check out the complete implementation along with other goodies in Castle Windsor Example Application over at GitHub.