Sam*_*Sam 7 asp.net-mvc autofac fluentvalidation
我需要能够提供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;
}
}
Run Code Online (Sandbox Code Playgroud)
我如何提供上下文并注册 ValidatorFactory
FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory());
Run Code Online (Sandbox Code Playgroud)
而不是将其与Autofac紧密结合,您可以DependencyResolver通过直接使用它来使其通常适用于任何:
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>>();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用任何类型DependencyResolver的强类型注册验证器,IValidator<T>它将始终最终解析.
我明白了这一点。如果您有ValidatorFactorytake IComponentContext,Autofac 会自动注入它。
验证器工厂
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;
}
}
Run Code Online (Sandbox Code Playgroud)
注册ValidatorFactory
FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure(x => x.ValidatorFactory = new ValidatorFactory());
Run Code Online (Sandbox Code Playgroud)