ASP.NET MVC 5: Inject a repository into an IValidatableObject

246 views Asked by At

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.

1

There are 1 answers

0
amedina On

Nope, it seems it's not possible because the MutableObjectModelBinder class, which is the one MVC 5 uses to create the corresponding object (SelectedFilteringCriteria in my case) from the action parameters, uses System.Activator instead of resolving the dependencies SelectedFilteringCriteria could have using the current DependencyResolver.

A workaround for this could be to do this inside the constructor of SelectedFilteringCriteria:

public SelectedFilteringCriteria()
{
    _filtersRepository = DependencyResolver.Current.GetService<IFiltersRepository>();
}

But that could drive to the Service Locator Antipattern. Your choice.