我正在使用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");
}
}
答案 0 :(得分:0)
假设它编译,Bind
位似乎没问题。 (现在猜猜......你可能需要将AssemblyScanner
位移到Ninject.Extensions.Conventions
,但你还没有告诉我们任何相关信息。)
你做错的主要事情是注入一个private
字段。正如维基所说,在V2中,田地不会被注入(非常确定私人也不会)。
您还没有显示BasePropertyFieldValidator
课程在哪里/如何被消费和/或出了什么问题。