using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentValidation; using Stylet; namespace Artemis.UI.Stylet { public class FluentValidationAdapter : IModelValidator { private readonly IValidator _validator; private T _subject; public FluentValidationAdapter(IValidator validator) { _validator = validator; } public void Initialize(object subject) { _subject = (T) subject; } public async Task> ValidatePropertyAsync(string propertyName) { // If someone's calling us synchronously, and ValidationAsync does not complete synchronously, // we'll deadlock unless we continue on another thread. return (await _validator.ValidateAsync(_subject, CancellationToken.None, propertyName).ConfigureAwait(false)) .Errors.Select(x => x.ErrorMessage); } public async Task>> ValidateAllPropertiesAsync() { // If someone's calling us synchronously, and ValidationAsync does not complete synchronously, // we'll deadlock unless we continue on another thread. return (await _validator.ValidateAsync(_subject).ConfigureAwait(false)) .Errors.GroupBy(x => x.PropertyName) .ToDictionary(x => x.Key, x => x.Select(failure => failure.ErrorMessage)); } } }