gpt4 book ai didi

c# - FluentValidation 即服务

转载 作者:行者123 更新时间:2023-11-30 14:02:59 25 4
gpt4 key购买 nike

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

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

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

最佳答案

我已经设法用 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.
}
}

关于c# - FluentValidation 即服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4810382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com