Quantcast
Channel: ASPNETWebStack Issue Tracker Rss Feed
Viewing all articles
Browse latest Browse all 7215

Edited Feature: Support IServiceProvider Injection for DataAnnotations validations through DependencyResolver [463]

$
0
0
I am not completely sure but at first glance, it seems to me that IServiceProvider for DataAnnotations validations is completely ignored in ASP.NET Web API.

Here is a quote from
Jeff Handley's blog post (http://jeffhandley.com/archive/2010/10/25/RiaServicesValidationContext.aspx):

"Consider the scenario where a validator needs to access the database; you certainly wouldn’t couple a validation method to your data access layer, would you? Instead, you would make your repository available as a service that your validation method can consume in a loosely-coupled manner. In order to easily support these scenarios, ValidationContext implements IServiceProvider. This interface requires a single method, GetService(Type). Using GetService, a validation method can access your repository without knowing how to instantiate or initialize it."

Here is the Validate method of the DataAnnotationsModelValidator class:

public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)
{
// Per the WCF RIA Services team, instance can never be null (if you have
// no parent, you pass yourself for the "instance" parameter).
ValidationContext context = new ValidationContext(container ?? metadata.Model, null, null);
context.DisplayName = metadata.GetDisplayName();

ValidationResult result = Attribute.GetValidationResult(metadata.Model, context);

if (result != ValidationResult.Success)
{
return new ModelValidationResult[] { new ModelValidationResult { Message = result.ErrorMessage } };
}

return new ModelValidationResult[0];
}

It would be great to inspect the global DependencyResolver and see whether there is any IServiceProvider type registered. If so, you can pass that into ValidationContext instead of passing null.

I am completely unsure if this is possible to implement because at the first glance, it seems that the validation part doesn't have any knowledge of the HttpConfiguration.

Edit:

Also, this would be much more useful for the IValidatableObject validation. A sample use case scenario here is to check an existence of a value inside the database.

Viewing all articles
Browse latest Browse all 7215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>