Created
October 19, 2016 17:38
-
-
Save maca88/4f10ec3ac66dd313cef52f4556b0fdd1 to your computer and use it in GitHub Desktop.
Example of a custom AsyncPredicateValidator using Nito.AsyncEx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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