Skip to content

Repository files navigation

ValidationProxy

ValidationProxy is a library that allows injection of dynamic validation rules in methods. It is designed with Web API services in mind and focuses on simplicity.

Example usage

Having the following service:

publicinterfaceICalculatorService{publicintCalculateFactorial(intnumber);}publicclassCalculatorService:ICalculatorService{publicintCalculateFactorial(intnumber){if(number==1){return1;}returnnumber*CalculateFactorial(number-1);}}

Assume we want to prevent CalculateFactorial from being called with numbers equal or less than zero and numbers above 10. Using ValidationProxy, this is achieved as follows:

  • Annotate the CalculateFactorial method.
publicconststringFactorialTooSmall="factorial-too-small";publicconststringFactorialTooLarge="factorial-too-large";[Validator(0,ValidationActions.FactorialTooLarge)][Validator(1,ValidationActions.FactorialTooSmall)]publicintCalculateFactorial(intnumber){if(number==1){return1;}returnnumber*CalculateFactorial(number-1);}
  • Add the validation interceptor in the Web API configuration.
services.AddValidatorInterceptor();
  • Configure ICalculatorService for interception.
services.AddProxiedScoped<ICalculatorService,CalculatorService>();
  • Add validation actions
ActionRepository.AddValidationAction(ValidationActions.FactorialTooSmall, info =>{varargument=info.ArgumentByPosition(0).AsInt();if(argument<=0){thrownewArgumentException($"Cannot calculate factorial for {argument}");}});ActionRepository.AddValidationAction(ValidationActions.FactorialTooLarge, info =>{varargument=info.ArgumentByName("number").AsInt();if(argument>10){thrownewArgumentException($"Will not calculate factorial for {argument}");}});

Validation actions can be removed or added dynamically during the lifetime of the application.

About

A proxy that allows dynamic validation of services method calls.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages