I am using fody.validar and it's work very well but I would like to use Ninject as the ValidationFactory instead of the home made one. Because I need to inject some services to validate things outside the context of the object being validated.
Can someone help me rewrite this:
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;
}
}
To use Ninject instead?
I found this code
public class FluentValidatorModule : NinjectModule
{
public override void Load()
{
AssemblyScanner
.FindValidatorsInAssemblyContaining<TextBoxValidator>()
.ForEach(match => Bind(match.InterfaceType).To(match.ValidatorType));
}
}
And hooked it up like this:
var kernel = new StandardKernel(new FluentValidatorModule());
But I don't know how to bind it all together.
Here is one of the validators I want to bind to a 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");
}
}
The
Binding bit seems OK, assuming it compiles. (Guessing now.. you may need to port theAssemblyScannerbit toNinject.Extensions.Conventionsbut you haven't told us anything about that.)The main thing you're doing wrong is injecting a
privatefield. As the wiki says, in V2, fields don't get injected (pretty sure privates don't either).You also haven't shown where / how the
BasePropertyFieldValidatorclass is being consumed and/or what's going wrong.