| | 1 | | using System.Runtime.ExceptionServices; |
| | 2 | | using Microsoft.Extensions.Hosting; |
| | 3 | | using Microsoft.Extensions.Options; |
| | 4 | |
|
| | 5 | | namespace Microsoft.Extensions.DependencyInjection; |
| | 6 | |
|
| 1 | 7 | | internal class ValidatorHostedService(IEnumerable<SimpleOptionValid> validators) : IHostedService |
| | 8 | | { |
| | 9 | | public Task StartAsync(CancellationToken cancellationToken) |
| 1 | 10 | | { |
| 1 | 11 | | List<Exception> exceptions = []; |
| | 12 | |
|
| 7 | 13 | | foreach (var validator in validators) |
| 2 | 14 | | { |
| | 15 | | try |
| 2 | 16 | | { |
| 2 | 17 | | validator(); |
| 2 | 18 | | } |
| 0 | 19 | | catch (OptionsValidationException ex) |
| 0 | 20 | | { |
| 0 | 21 | | exceptions.Add(ex); |
| 0 | 22 | | } |
| 2 | 23 | | } |
| | 24 | |
|
| 1 | 25 | | if (exceptions.Any()) |
| 0 | 26 | | { |
| 0 | 27 | | if (exceptions.Count == 1) |
| 0 | 28 | | { |
| | 29 | | // Rethrow if it's a single error |
| 0 | 30 | | ExceptionDispatchInfo.Capture(exceptions[0]).Throw(); |
| 0 | 31 | | } |
| | 32 | |
|
| 0 | 33 | | if (exceptions.Count > 1) |
| 0 | 34 | | { |
| | 35 | | // Aggregate if we have many errors |
| 0 | 36 | | throw new AggregateException(exceptions); |
| | 37 | | } |
| 0 | 38 | | } |
| | 39 | |
|
| 1 | 40 | | return Task.CompletedTask; |
| 1 | 41 | | } |
| | 42 | | public Task StopAsync(CancellationToken cancellationToken) |
| 1 | 43 | | { |
| 1 | 44 | | return Task.CompletedTask; |
| 1 | 45 | | } |
| | 46 | |
|
| | 47 | |
|
| | 48 | | } |