-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidationAdapter.cs
39 lines (34 loc) · 1.11 KB
/
ValidationAdapter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using FluentValidation;
using Stylet;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CreditCalc
{
public class ValidationAdapter<T> : IModelValidator<T>
{
private readonly IValidator<T> validator;
private T subject;
public ValidationAdapter(IValidator<T> validator)
{
this.validator = validator;
}
public void Initialize(object subject)
{
this.subject = (T)subject;
}
public Task<IEnumerable<string>> ValidatePropertyAsync(string propertyName)
{
var errors = this.validator.Validate(this.subject, propertyName).Errors.Select(x => x.ErrorMessage);
return Task.FromResult(errors);
}
public async Task<Dictionary<string, IEnumerable<string>>> ValidateAllPropertiesAsync()
{
// If someone's calling us synchronously, and ValidationAsync does not complete synchronously,
// we'll deadlock unless we continue on another thread.
return (await this.validator.ValidateAsync(this.subject).ConfigureAwait(false))
.Errors.GroupBy(x => x.PropertyName)
.ToDictionary(x => x.Key, x => x.Select(failure => failure.ErrorMessage));
}
}
}