diff --git a/src/Validation/src/ValidateContext.cs b/src/Validation/src/ValidateContext.cs index aca47fc1e118..8d4851768843 100644 --- a/src/Validation/src/ValidateContext.cs +++ b/src/Validation/src/ValidateContext.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; - namespace Microsoft.Extensions.Validation; /// @@ -10,7 +8,7 @@ namespace Microsoft.Extensions.Validation; /// public sealed class ValidateContext { - private Dictionary>? _validationErrors; + private Dictionary>? _validationErrors; /// /// Initializes a new instance of . @@ -46,7 +44,7 @@ public ValidateContext() /// There are no guarantees whether or not this dictionary is lazy. Usages should treat null and empty dictionary the same. /// public IReadOnlyDictionary>? ValidationErrors - => _validationErrors?.ToDictionary(kvp => kvp.Key, kvp => (IReadOnlyList)kvp.Value.AsReadOnly()).AsReadOnly(); + => _validationErrors; /// /// Gets or sets the current depth in the validation hierarchy. @@ -62,15 +60,14 @@ public IReadOnlyDictionary>? ValidationEr /// The validation error to add. public void AddValidationError(ValidationError validationError) { - _validationErrors ??= new Dictionary>(); - + _validationErrors ??= new Dictionary>(); if (!_validationErrors.TryGetValue(validationError.Path, out var existingErrors)) { _validationErrors.Add(validationError.Path, new List { validationError }); } else { - existingErrors.Add(validationError); + ((List)existingErrors).Add(validationError); } } } diff --git a/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidatableParameterInfoTests.cs b/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidatableParameterInfoTests.cs index d11c0e48590e..60dacb1d3dc5 100644 --- a/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidatableParameterInfoTests.cs +++ b/src/Validation/test/Microsoft.Extensions.Validation.Tests/ValidatableParameterInfoTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.DataAnnotations; +using System.Diagnostics; using System.Reflection; namespace Microsoft.Extensions.Validation.Tests; @@ -108,6 +109,29 @@ public async Task Validate_WithEnumerableOfValidatableType_ValidatesEachItem(boo Assert.Equal("The Name field is required.", error.Value.Select(e => e.ErrorMessage).Single()); } + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Validate_WithEnumerableOfValidatableType_ValidatesEachItem_AccessingValidationErrorsDoesNotCopy(bool useAsync) + { + var (provider, options) = GeneratedValidationTestHelpers.CreateValidationServices(); + var parameterInfo = GetParameter(nameof(ParameterActions.PeopleParameter)); + Assert.True(options.TryGetValidatableParameterInfo(parameterInfo, out var paramInfo)); + var context = GeneratedValidationTestHelpers.CreateContext(provider, options); + + var array = new ParameterPerson[10000]; + for (var i = 0; i < array.Length; i++) + { + array[i] = new ParameterPerson(); + } + + await ValidateAsync(paramInfo, array, context, useAsync, default); + + Assert.NotNull(context.ValidationErrors); + Assert.True(ReferenceEquals(context.ValidationErrors, context.ValidationErrors)); + Assert.Equal(array.Length, context.ValidationErrors.Count); + } + [Theory] [InlineData(true)] [InlineData(false)] @@ -158,37 +182,6 @@ public async Task Validate_ExceptionDuringValidation_Rethrown(bool useAsync) Assert.True(context.ValidationErrors is null || context.ValidationErrors.Count == 0); } - [Theory] - [InlineData(true)] - [InlineData(false)] - public async Task ValidationErrors_ReturnsImmutableCollections(bool useAsync) - { - var (provider, options) = GeneratedValidationTestHelpers.CreateValidationServices(); - var parameterInfo = GetParameter(nameof(ParameterActions.RequiredParameter)); - Assert.True(options.TryGetValidatableParameterInfo(parameterInfo, out var paramInfo)); - var context = GeneratedValidationTestHelpers.CreateContext(provider, options); - - await ValidateAsync(paramInfo, null, context, useAsync, default); - - var errors = context.ValidationErrors; - Assert.NotNull(errors); - - // The outer dictionary must not be castable to a mutable Dictionary - Assert.False(errors is Dictionary>); - - // The value lists must not be castable to a mutable List - var value = Assert.Single(errors).Value; - Assert.False(value is List); - - // Attempting to mutate the outer dictionary must throw - Assert.Throws(() => - ((IDictionary>)errors)["newKey"] = []); - - // Attempting to mutate a value list must throw - Assert.Throws(() => - ((IList)value).Add(new ValidationError { Name = "x", Path = "x", ErrorMessage = "x", Container = null })); - } - private static ParameterInfo GetParameter(string methodName) => typeof(ParameterActions).GetMethod(methodName)!.GetParameters()[0]; }