In MVC, an instance of ModelValidatorProvider is created and called to validate the model for each request. This means that in a DI environment, it may depend on objects covered by a single request, such as the context of a unit of work or database. In the Web API, this seems to have changed significantly. Instead of being instantiated on demand, ModelValidatorProvider seems to be durable and is instantiated on application startup. The WebAPI then caches the results from ModelValidatorProvider per-type, which means that ModelValidator cannot accept DI dependencies.
I am trying to implement my ModelValidator to use a factory using the Locator service (please, no automatic โagainst templateโ comments!). This would allow me to create an internal validator object within each request that could accept container dependencies. However, I cannot get the Dependency Resonance or container covered by the current request from this ModelValidator , which is essentially related to Singleton. I tried to use GlobalConfiguration.Configuration.DependencyResolver , but this only returns services with global reach (from the root area, also here)
I work in Autofac, so an autofocus solution would be suitable (for example, MVC has AutofacDependencyResolver.Current , which internally uses DependencyResolver.GetService ). There is no equivalent in WebAPI integration, presumably due to the reason mentioned above, when the global DependencyResolver returns only services with global reach.
The reason I'm trying to do this (as well as for my own use) is to implement the Web API integration for FluentValidation, which currently does not exist. So far, there have been two attempts, but none of them cope with the problem of dependency injection and instead leads to the creation of one static ModelValidator.
Things I've tried so far:
- Using
GlobalConfiguration.Configuration.DependencyResolver (returns objects from the root area) - Taking dependency on
Func<IComponentContext> (always returns the root context)
The answer, which has since been removed, suggested removing the IModelValidatorProvider service from the web API configuration. This should have been done using reflection, since the interface and implementation classes are defined as internal, but it really improved the validators (since ModelValidator was created for each request). However, there is significant success associated with this, thanks to the use of reflection to test validators on the model and each property that it has, so I do not want to use this option.
Filip W's answer suggests using HttpRequestMessage to get the dependency region, but I have not found anything like HttpRequestMessage.Current that would provide access to this object from a long-lived object - if it were possible, I believe everything will fall into place.