我在尝试将FluentValidation与Unity集成时遇到了一些麻烦。
我有一个工厂类
public class UnityValidatorFactory : FluentValidation.ValidatorFactoryBase
{
private readonly IUnityContainer _container;
public UnityValidatorFactory()
{
_container = null;
}
public UnityValidatorFactory(IUnityContainer container)
{
_container = container;
}
public override FluentValidation.IValidator CreateInstance(Type validatorType)
{
return _container.Resolve(validatorType) as FluentValidation.IValidator;
}
}
问题是它不会在数据类中实例化
public class Payment : IValidatableObject
{
private readonly IValidator _validator = new PaymentValidator();
public string paymentType { get; set; }
//etc
public Payment(IValidatorFactory validatorFactory)
{
**//ValidatorFactory is always null!**
_validator = validatorFactory.GetValidator(typeof(Payment));
}
}
这是我尝试使用unity
注册工厂类的代码container.RegisterType<IValidatorFactory, UnityValidatorFactory>(new ContainerControlledLifetimeManager());
但是工厂始终为空。知道我做错了吗?
答案 0 :(得分:0)
我的建议是下一个。
创建所有验证器并实现下一个接口,将其命名为:IModelValidator
public interface IModelValidator
{
}
//example of a validator class
public class MyModelValidator : AbstractValidator<MyModel>, IModelValidator
{
public MyModelValidator ()
{
CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(x => x.yourField)
.NotNull()
.NotEmpty()
.WithMessage("You need to enter yourField");
}
}
//this is to register all your interfaces on the container
void RegisterValidators(IUnityContainer container)
{
var type = typeof(IValidator<>);
var validators = AssemblyScanner.FindValidatorsInAssemblyContaining<IModelValidator>();
validators.ForEach(validator => container.RegisterType(validator.InterfaceType, validator.ValidatorType));
}
//与MVC集成,创建容器时应该在Global.asax中执行此操作
public static ConfigureFluentValidation(IUnityContainer container)
{
var fluentValidationModelValidatorProvider = new FluentValidationModelValidatorProvider(new UnityValidationFactory(container));
//disables the implicit required validator being added for both the DataAnnotationsModelProvider, as well as the FluentValidationModelValidatorProvider.
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
fluentValidationModelValidatorProvider.AddImplicitRequiredValidator = false;
//adds the new model validator provider to the list of model validator providers used by the MVC framework.
ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);
}
现在,在您发布要验证的信息的控制器方法中,您将看到是否将您的字段留空ModelState.IsValid
具有错误值