【问题标题】:FluentValidation, Autofac, and child collection of interfaced objectsFluentValidation、Autofac 和接口对象的子集合
【发布时间】:2014-08-19 23:23:00
【问题描述】:

我想验证一个包含以下类型子集合的对象:ICollection<IEntity>

有多个实现 IEntity 的类。我对这些类中的每一个都有一个验证器。它们都继承自 ValidatorAbstract。

如何在父类中为集合中的每个子对象分配适当的验证器?

我使用 Autofac 来注入依赖项。我猜我需要使用这个方法:

RuleForEach(n=>n.ChildCollection).SetValidator(container.Resolve<?>)

但是,SetValidator 没有每个对象类型的上下文。

【问题讨论】:

  • 你需要什么信息来解决你想要的服务?
  • Autofac 包含一些 CustomValidator 和 IValidator 之间的绑定,其中 ChildEntity : IEntity。如果需要,我可以将 Autofac 的容器注入到父验证器类中。

标签: generics autofac fluentvalidation


【解决方案1】:

看起来我找到了我正在寻找的答案。关键是创建一个从 NoopPropertyValidator 派生的自定义验证器类,并为其提供 Autofac 容器(或其他 IOC 容器)

public class EntityCollectionValidator<TEntity> : NoopPropertyValidator
{
    private readonly IComponentContext _container;

    public EntityCollectionValidator(IComponentContext container)
    {
        _container = container;
    }

    public override IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context)
    {
        var results = new List<ValidationFailure>();

        var collection = context.PropertyValue as IEnumerable<TEntity>;
        if (collection == null) return results;

        foreach (var entity in collection)
        {
            var interfaceType = typeof (IValidator<>).MakeGenericType(entity.GetType());
            if (!_container.IsRegistered(interfaceType)) continue;

            var validator = _container.Resolve(interfaceType) as IValidator<TEntity>;

            if (validator != null)
                results.AddRange(validator.Validate(entity).Errors);
        }

        return results;
    }
}

在验证类中,实例化它的方法是在通用资源集合上执行此操作:

    RuleFor(n => n.ChildCollection)SetValidator(new EntityCollectionValidator<IChild>(container));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2012-02-15
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多