IDataErrorInfo: the service locator way

If you read my blog backward you will find some implementations of IDataErrorInfo. I’ve even implemented IDataErrorInfo with AOP in unhaddins. I found the interface useful when I want to show validations errors through a DataBinding infrastructure, WPF, WinForms or even Asp.Net MVC.

In my last post, there are some comments about service locator:

  1. Mauricio Scheffer said; “It's just easier and more maintainable to use real dependency injection.”
  2. Ivan Korneliuk said; “I prefer to inject IServiceLocator abstraction for such classes, rather than using global ServiceLocator.”

And I agree with both, but there are corner cases.

So, this is all I need to implement IDataErrorInfo in my base entity:

public class BaseEntity : ComparableEntity, IDataErrorInfo
{
    private static IEntityValidator entityValidator;

    private static IEntityValidator EntityValidator
    {
        get
        {
            if (entityValidator == null)
            {
                return entityValidator 
                        = ServiceLocator
                                .Current
                                .GetInstance<IEntityValidator>();
            }
            return entityValidator;
        }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            var errors = EntityValidator
                    .Validate(this, columnName)
                    .Select(iv => iv.Message)
                    .ToArray();
            return string.Join(Environment.NewLine, errors);
        }
    }

    string IDataErrorInfo.Error
    {
        get
        {
            var errors = EntityValidator
                .Validate(this)
                .Select(iv => iv.Message)
                .ToArray();

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

Yes, there are some posts about dependency injection in entities, and I’ve done months ago, but it is over complicated for this case. So, with this code, I am not injecting IServiceLocator, and I am not injecting IValidatorEngine. I’m just using a good pattern :)

You can test this code with the code in my previous post.


blog comments powered by Disqus
  • Categories

  • Archives