-1

I had to investigate some exception at production, and then I found this code that uses FluentValidation:

(inside async method)
var validator = new SomeCustomValidator();
var validationResult = validator.ValidateAsync(request).Result.ValidateRepositoryAsync(request, someRepository);

PS: The method ValidateRepositoryAsync is a custom extension from our project.

To do a little bit refactoring on it, I just changed to:

(inside async method)
ValidationResult validationResult;
var validator = new SomeCustomValidator();
validationResult = await validator.ValidateAsync(request);
validationResult = await validationResult.ValidateRepositoryAsync(request, someRepository);

So, this codes needs to execute first the ValidateAsync, await for it, and then with the result execute the ValidateRepositoryAsync.

Now the question is, I was wondering if there's another way to do that, maybe in an one line of code, with ContinueWith, or this is the cleaner way to solve this issue?

That's the closer I got, but that doesn't seem cleaner to read:

var validator = new SomeCustomValidator();
var validationResult = await (await validator.ValidateAsync(request)).ValidateRepositoryAsync(request, someRepository);

Any thoughts on that?

Thanks!

Sawd
  • 185
  • 3
  • 13
  • 3
    No problem, chaining await calls like that is the recommended way. Note that `Result` definitely isn't *causing* the issue. To understand the root cause, you need to check the `InnerException` property of your AggregateException. As a good practice, you should log `exception.ToString()`, you'll get all the information in there – Kevin Gosse Oct 06 '20 at 20:17
  • 3
    Use an intermediate variable for cleanliness but the two awaits are correct – Aluan Haddad Oct 06 '20 at 20:17
  • @KevinGosse Thank you. And I did a little more research on the inner exception itself, and it seems the problem is a random refusal in db connection. Because of that, I will remove the part I was talking about the exception. But in fact, I think my question would be still useful for someone, as I saw other posts here asking how to do multiple awaits in "one line of code" or something. Don't know why my question was downvoted though. – Sawd Oct 06 '20 at 21:42
  • @AluanHaddad Thanks for your suggestion. – Sawd Oct 06 '20 at 21:43

1 Answers1

1

Since ValidateRepositoryAsync is your own extension method, perhaps you could create another prototype of it, this one accepting the unawaited task.

static async Task<ValidationResult> ValidateRepositoryAsync(this Task<ValidationResult> source, request, someRepository)
{
    var result = await source;
    return await result.ValidateRepositoryAsync(request, someRepository);
}

With this version in place, all you have to do is

validationResult = await validator.ValidateAsync(request).ValidateRepositoryAsync(request, someRepository);
John Wu
  • 50,556
  • 8
  • 44
  • 80