Good day!

Can someone suggest?

The ASP.NET WEB API project uses the Ninject IoC container.

Link to the post of the author.

Question: How to pass an attribute to [FluentValidationActionFilter(???)] IDependencyResolver. If possible, I would like to see an example.

  public class FluentValidationActionFilter : ActionFilterAttribute { private readonly IDependencyResolver _resolver; public FluentValidationActionFilter(IDependencyResolver resolver) { _resolver = resolver; } public override void OnActionExecuting(HttpActionContext actionContext) { var actionArguments = GetTheActionArguments(actionContext); if (actionArguments == null) { return; } foreach (var actionArgument in actionArguments) { if (actionArgument.Value == null) { var actionArgumentDescriptor = GetActionArgumentDescriptor(actionContext, actionArgument.Key); if (actionArgumentDescriptor.IsOptional) { continue; } var validator = GetValidatorForActionArgumentType(actionArgumentDescriptor.ParameterType); if (validator == null) { continue; } actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest); return; } else { var validator = GetValidatorForActionArgument(actionArgument.Value); if (validator == null) { continue; } var validationResult = validator.Validate(actionArgument.Value); if (validationResult.IsValid) { continue; } WriteErrorsToModelState(validationResult, actionContext); return; } } } private static IEnumerable<KeyValuePair<string, object>> GetTheActionArguments(HttpActionContext actionContext) { return actionContext.ActionArguments .Select(argument => argument); } private static HttpParameterDescriptor GetActionArgumentDescriptor(HttpActionContext actionContext, string actionArgumentName) { return actionContext.ActionDescriptor .GetParameters() .SingleOrDefault(prm => prm.ParameterName == actionArgumentName); } private IValidator GetValidatorForActionArgument(object actionArgument) { var abstractValidatorType = typeof (IValidator<>); var validatorForType = abstractValidatorType.MakeGenericType(actionArgument.GetType()); return _resolver.GetService(validatorForType) as IValidator; } private IValidator GetValidatorForActionArgumentType(Type actionArgument) { var abstractValidatorType = typeof(IValidator<>); var validatorForType = abstractValidatorType.MakeGenericType(actionArgument); return _resolver.GetService(validatorForType) as IValidator; } private static void WriteErrorsToModelState(ValidationResult validationResults, HttpActionContext actionContext) { foreach (var error in validationResults.Errors) { actionContext.ModelState.AddModelError(error.PropertyName, error.ErrorMessage); } } } 

Thanks a lot, everyone!

  • one
    Here is an opinion. - i-one
  • one
    Although, sorry, you're trying to inject Resolver , not IDependency . However, the answer with en-SO, in my opinion, still deserves a reading (plus there is a link to the article and to another answer). - i-one

0