DataAnnotations abstraction + pseudo-engine in uNhAddIns

At uNhAddIns we have something called IEntityValidator and it is implemented for Castle Validations, NHibernate Validator, Validation Application Block and DataAnnotations. You can read Fabio Maulo’s post here.

Another interesting point of the DataAnnotations implementation is that I wrote a cache for the attributes and properties (there is not concept of engine in data annotations). You can see the whole pseudo-engine here.

Usage

Step 1, register your IEntityValidator in your container;

container.Register(Component.For<IEntityValidator>()
    .ImplementedBy<uNhAddIns.DataAnnotations.EntityValidator>()
    .Named("da-entity-validator"));

Step 2, inject your IEntityValidator any where, an example usage is in a base viewmodel (wpf), for implementing IDataErrorInfo

public class ViewModelBase
    : IDataErrorInfo
{
    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            var errors = ServiceLocator.Current
                .GetInstance<IEntityValidator>("da-entity-validator")
                .Validate(this, columnName)
                .Select(iv => iv.Message)
                .ToArray();

            return string.Join(Environment.NewLine, errors);
        }
    }

    string IDataErrorInfo.Error
    {
        get
        {
            var errors = ServiceLocator.Current
                .GetInstance<IEntityValidator>("da-entity-validator")
                .Validate(this)
                .Select(iv => iv.Message)
                .ToArray();

            return string.Join(Environment.NewLine, errors);
        }
    }
}

I have registered the service with a key because, I've two services for IEntityValidator in my application. One for NHV used to validate entities, and another one for Data Annotations used to validate ViewModels.


blog comments powered by Disqus
  • Categories

  • Archives