fluentValidation集成到autofac
废话不说直接上代码
// 首先实现ValidatorFactory public class DependencyResolverValidatorFactory : ValidatorFactoryBase { public override IValidator CreateInstance(Type validatorType) { return DependencyResolver.Current.GetService(validatorType) as IValidator; } }
//配置FluentValidation public class FluentValidationConfig { public static void ConfigureContainer() { var factory = new DependencyResolverValidatorFactory(); ModelValidatorProviders.Providers .Add(new FluentValidationModelValidatorProvider(factory)); DataAnnotationsModelValidatorProvider .AddImplicitRequiredAttributeForValueTypes = false; ValidatorOptions.ResourceProviderType = typeof(ValidationResources); ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure; } }
//在autofac中注册继承自AbstractValidator的验证类 AssemblyScanner .FindValidatorsInAssemblyContaining<AddressValidator>() .ForEach(x => builder.RegisterType(x.ValidatorType).As(x.InterfaceType).SingleInstance()); //该类所在程序集内的所有继承自AbstractValidator的验证类都会被注册到autofac容器内 public class AddressValidator : AbstractValidator<Address> { public AddressValidator () { RuleFor(x => x.Name).NotEmpty().WithLocalizedName(()=>"收件人"); RuleFor(x => x.Email).NotEmpty().EmailAddress(); RuleFor(x => x.Mobile).NotEmpty().Mobile(); } }
fluentValidation集成到autofac的好处
//如果fluentValidation不使用autofac容器,那么需要在每个asp.net mv action中调用 Address address = new Address(); AddressValidator validator = new AddressValidator(); ValidationResult results = validator.Validate(address); //或者 [Validator(typeof(AddressValidator))]//此行是重点 public class Address { public string Name { get; set; } public string Mobile { get; set; } public string Email { get; set; } public string Details { get; set; } } //用了autofac 上面两种都不需要,在action像没有用到fluentvalidation那样直接: if (!ModelState.IsValid) { return View(model); }