I have a class that implements the IValidatableObject interface, in order to validate the incoming data introduced by the user. The problem is that in order to validate that data, I need to use a class that implements the data repository pattern, which is in another assembly. Something like this:
public class SelectedFilteringCriteria : IValidatableObject
{
private IFiltersRepository _filtersRepository;
public SelectedFilteringCriteria(IFiltersRepository filtersRepository)
{
_filtersRepository = filtersRepository;
}
public int? SelectedValue { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
var valueOk = _filtersRepository.GetFilters().Any(
filter => filter.Value == SelectedValue
);
if (!valueOk)
{
results.Add(new ValidationResult("Not good :("));
}
return results;
}
}
The dependency container I'm using is Ninject. I would like to know if there's a way to tell MVC to inject the repository class into the IValidatableObject when it's going to be created.
Nope, it seems it's not possible because the
MutableObjectModelBinderclass, which is the one MVC 5 uses to create the corresponding object (SelectedFilteringCriteriain my case) from the action parameters, usesSystem.Activatorinstead of resolving the dependenciesSelectedFilteringCriteriacould have using the currentDependencyResolver.A workaround for this could be to do this inside the constructor of
SelectedFilteringCriteria:But that could drive to the Service Locator Antipattern. Your choice.