我需要能够将IComponentContext提供给我的ValidatorFactory来解析FluentValidation Validators.我有点卡住了.
ValidatorFactory
public class ValidatorFactory : ValidatorFactoryBase { private readonly IComponentContext context; public ValidatorFactory(IComponentContext context) { this.context = context; } public override IValidator CreateInstance(Type validatorType) { return context.Resolve(validatorType) as IValidator; } }
如何提供上下文并注册ValidatorFactory
FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory());
解决方法
您可以通过直接使用它来使其通常适用于任何DependencyResolver,而不是将其与Autofac紧密结合:
public class ModelValidatorFactory : IValidatorFactory { public IValidator GetValidator(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return DependencyResolver.Current.GetService(typeof(IValidator<>).MakeGenericType(type)) as IValidator; } public IValidator<T> GetValidator<T>() { return DependencyResolver.Current.GetService<IValidator<T>>(); } }
然后,您可以将任何类型的DependencyResolver注册为验证器,作为强类型IValidator< T>它总会最终解决.