Interceptors around key operations:

Jul 24, 2012 at 6:20 AM

Would love to see some event listeners around key events.  In particular I'm looking for a pre-insert/update event listener so I can put a guard in to ensure only valid objects get persisted.  I do it today using FluentValidation with NHibernate:

public class EntityValidationInterceptor : IPreInsertEventListener, IPreUpdateEventListener, IPreCollectionUpdateEventListener
{
    private readonly AttributedValidatorFactory validatorFactory = new AttributedValidatorFactory();
    private static readonly ValidationResult emptyValidationResult = new ValidationResult();

    public bool OnPreInsert(PreInsertEvent @event)
    {
        Validate(@event.Entity, @event.Session.EntityMode);
        return false;
    }

    public bool OnPreUpdate(PreUpdateEvent @event)
    {
            Validate(@event.Entity, @event.Session.EntityMode);
            return false;
    }

    public void OnPreUpdateCollection(PreCollectionUpdateEvent @event)
    {
        var owner = @event.AffectedOwnerOrNull;
        if (!ReferenceEquals(null, owner))
        {
            Validate(owner, @event.Session.EntityMode);
        }
    }

    protected void Validate(object entity, EntityMode mode)
    {
        if (entity == null || mode != EntityMode.Poco) return;

        var validator = validatorFactory.GetValidator(entity.GetType());
        var result = validator != null ? validator.Validate(entity) : emptyValidationResult;
        if(!result.IsValid)
        {
            throw new ValidationException(result.Errors);
        }
    }
}

Coordinator
Jul 26, 2012 at 1:32 AM

Sure.  I'll take a look at adding this in a future release.

Coordinator
Jul 26, 2012 at 1:32 AM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.