From d01bb92ed11ba5584876c2e16549bd3b6461df23 Mon Sep 17 00:00:00 2001 From: Daniel Petrov Date: Thu, 14 Oct 2021 19:09:49 +0200 Subject: [PATCH] Remove extra call to PropertyInfo.GetValue(object) Fix #52905 --- .../src/ConfigurationBinder.cs | 10 ++++------ .../tests/ConfigurationBinderTests.cs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs index f13edb1872ebe..2cbcfbb1c089e 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs @@ -248,19 +248,17 @@ private static void BindProperty(PropertyInfo property, object instance, IConfig return; } - object propertyValue = property.GetValue(instance); bool hasSetter = property.SetMethod != null && (property.SetMethod.IsPublic || options.BindNonPublicProperties); - if (propertyValue == null && !hasSetter) + if (!hasSetter) { - // Property doesn't have a value and we cannot set it so there is no - // point in going further down the graph + // The property cannot be set so there is no point going further return; } - propertyValue = GetPropertyValue(property, instance, config, options); + object propertyValue = GetPropertyValue(property, instance, config, options); - if (propertyValue != null && hasSetter) + if (propertyValue != null) { property.SetValue(instance, propertyValue); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs b/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs index c5dbd9d90821a..6629557ce89be 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs @@ -117,6 +117,11 @@ public class ByteArrayOptions public byte[] MyByteArray { get; set; } } + public class GetterOnlyOptions + { + public string MyString => throw new NotImplementedException(); + } + [Fact] public void CanBindIConfigurationSection() { @@ -343,6 +348,20 @@ public void ThrowsIfPropertyInConfigMissingInNestedModel() Assert.Equal(expectedMessage, ex.Message); } + [Fact] + public void DoesNotExecuteGetterIfNoSetter() + { + var dic = new Dictionary + { + {"MyString", "hello world"} + }; + var configurationBuilder = new ConfigurationBuilder(); + configurationBuilder.AddInMemoryCollection(dic); + var config = configurationBuilder.Build(); + + var _ = config.Get(); + } + [Fact] public void GetDefaultsWhenDataDoesNotExist() {