José F. Romaniello

Las aventuras y desventuras de un codificador.

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.

| More

3 comentarios:

Nice, Jose.

But now I'm curious about your ComparableEntity. Could you show it for us?

thanks!

José F. Romaniello dijo...

yes, is exactly this:
http://code.google.com/p/unhaddins/source/browse/#svn/trunk/uNhAddIns/uNhAddIns.Entities
<http:>look
Entity.... "Comparable" it has the Equality members. A more apropiate name
will be something like "EquatableEntity", or just entity.
</http:>

Yes, I see the point now. Very usefull. Thanks a lot!

Publicar un comentario