我正在使用 fody.validar,它工作得很好,但我想使用 Ninject 作为 ValidationFactory 而不是自制的。因为我需要注入一些服务来验证被验证对象上下文之外的东西。
有人可以帮我重写这个:
public static class ValidationFactory
{
static readonly Dictionary<RuntimeTypeHandle, IValidator> Validators = new Dictionary<RuntimeTypeHandle, IValidator>();
public static IValidator GetValidator(Type modelType)
{
IValidator validator;
if (!Validators.TryGetValue(modelType.TypeHandle, out validator))
{
var typeName = modelType.Name + "Validator";
var type = Type.GetType("Nexcom.KnownTypes.PropertyFields.Validation." + typeName, true);
validator = (IValidator)Activator.CreateInstance(type);
Debug.Assert(validator != null);
Validators.Add(modelType.TypeHandle, validator);
}
return validator;
}
}
要改用 Ninject 吗?
我找到了这段代码
public class FluentValidatorModule : NinjectModule
{
public override void Load()
{
AssemblyScanner
.FindValidatorsInAssemblyContaining<TextBoxValidator>()
.ForEach(match => Bind(match.InterfaceType).To(match.ValidatorType));
}
}
并像这样连接起来:
var kernel = new StandardKernel(new FluentValidatorModule());
但我不知道如何将它们绑定在一起。
这是我要绑定到 PropertyField 的验证器之一:
public class BasePropertyFieldValidator<T> : AbstractValidator<T> where T: IPropertyField
{
[Inject] private IUniquePropertyName _uniqueProperty;
public BasePropertyFieldValidator()
{
RuleFor(c => c.Name)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.WithMessage("Please specify a name")
.Matches(UniquePropertyName.ValidNameRegex)
.WithMessage("Name can only contain: a-z, A-Z, 0-9, _")
.Must(_uniqueProperty.NameIsUnique)
.WithMessage("Please enter a unique name");
}
}