Skip to content

Instantly share code, notes, and snippets.

@maca88
Created October 19, 2016 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maca88/4f10ec3ac66dd313cef52f4556b0fdd1 to your computer and use it in GitHub Desktop.
Save maca88/4f10ec3ac66dd313cef52f4556b0fdd1 to your computer and use it in GitHub Desktop.
Example of a custom AsyncPredicateValidator using Nito.AsyncEx
namespace WpfApplication1
{
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using FluentValidation;
using FluentValidation.Validators;
using Nito.AsyncEx;
public class TestModel {
public string Name { get; set; }
}
public class TestModelValidator : AbstractValidator<TestModel> {
public TestModelValidator() {
RuleFor(m => m.Name)
.MustAsync(async (s, token) => {
await Task.Yield(); // Here we will avoid a deadlock in a single threaded context by using our custom predicate validator
return true;
});
}
}
public class AsyncPredicateValidatorEx : AsyncPredicateValidator {
public AsyncPredicateValidatorEx(AsyncPredicate predicate) : base(predicate) {
}
protected override bool IsValid(PropertyValidatorContext context) {
return AsyncContext.Run(async () => await IsValidAsync(context, new CancellationToken()));
}
}
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
// Setting our custom async predicate validator that uses Nito.AsyncEx AsyncContext to avoid deadlocks
ValidatorOptions.AsyncValidatorFactory = predicate => new AsyncPredicateValidatorEx(predicate);
var model = new TestModel {Name = "test"};
var result = new TestModelValidator().Validate(model);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment