3

我正在使用 FluentValidation 2 来验证某些实体。我想创建一个IValidationService可以传递给其他服务以允许他们执行验证的服务。我想像这样公开它:

public interface IValidationEngine
{
    IEnumerable<ValidationError> Validate<T>(T entity);
}

ValidationError封装我的验证错误的类在哪里。理想情况下,我不想将特定验证器暴露给我的一项服务(例如OrderValidator)。我希望验证服务能够构建/找到正确的验证器。FV 是否内置了任何东西来定位特定类型的验证器(并且它在内部缓存)?或者,我是否必须走这IValidatorFactory条路线,然后将每个验证器与我的 IoC 容器连接起来?

4

1 回答 1

9

我已经设法用这种IValidatorFactory方法解决了这个问题。我正在使用 Ninject,因此需要更改下面的特定 IoC 详细信息。

public interface IValidationService
{
    IEnumerable<ValidationError> Validate<T>(T entity)
        where T : class;
}

public class FluentValidationService : IValidationService
{
    private readonly IValidatorFactory validatorFactory;

    public FluentValidationService(IValidatorFactory validatorFactory)
    {
        this.validatorFactory = validatorFactory;
    }

    public IEnumerable<ValidationError> Validate<T>(T entity)
        where T : class
    {
        var validator = this.validatorFactory.GetValidator<T>();
        var result = validator.Validate(entity);
        return result.Errors.Select(e => new ValidationError(e.PropertyName, e.ErrorMessage));
    }
}

// Then implement FV's IValidatorFactory:

public class NinjectValidatorFactory : ValidatorFactoryBase
{
    private readonly IKernel kernel;

    public NinjectValidatorFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public override IValidator CreateInstance(Type validatorType)
    {
        return kernel.TryGet(validatorType) as IValidator;
    }
}

// I then wire both of these in a Ninject Module:

public class ValidationModule : NinjectModule
{
    public override void Load()
    {
        this.Bind<IValidationService>().To<FluentValidationService>().InRequestScope(); // Specific to MVC.
        this.Bind<IValidatorFactory>().To<NinjectValidatorFactory>().InRequestScope();
    }
}

// Then I can use it inside a service:

public class FooService
{
    private readonly IValidationService validationService;

    public FooService(IValidationService validationService)
    {
        this.validationService = validationService;
    }

    public bool Add(Foo foo)
    {
        if(this.validationService.Validate(foo).Any())
        {
            // Handle validation errors..
        }

        // do other implementation details here.
    }
}
于 2011-01-27T14:42:02.520 回答