Skip to content

Commit

Permalink
Merge pull request #1369 from autofac/feature/ignore-required-props-i…
Browse files Browse the repository at this point in the history
…n-prop-autowiring

Ignore required properties in the default autowiring property selector.
  • Loading branch information
tillig authored Mar 6, 2023
2 parents 2f5418f + 6f335e7 commit 1910177
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
13 changes: 13 additions & 0 deletions src/Autofac/Core/Activators/DefaultPropertySelector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Reflection;
using System.Runtime.CompilerServices;

namespace Autofac.Core;

Expand Down Expand Up @@ -55,6 +56,18 @@ public virtual bool InjectProperty(PropertyInfo propertyInfo, object instance)
return false;
}

#if NET7_0_OR_GREATER
if (propertyInfo.GetCustomAttribute<RequiredMemberAttribute>() is not null)
{
// The default property selector should not inject required properties,
// to avoid duplication with the injection automatically applied inside the
// ReflectionActivator.
// Any other form of activator (lambda, instance) would generally already be required to
// set the required properties in order to create the instance.
return false;
}
#endif

if (PreserveSetValues && propertyInfo.CanRead)
{
try
Expand Down
14 changes: 13 additions & 1 deletion test/Autofac.Test/Core/DefaultPropertySelectorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,20 @@ public class DefaultPropertySelectorTests
[InlineData(true, "PublicPropertyNoSet", false)]
[InlineData(true, "PublicPropertyThrowsOnGet", false)]
[InlineData(false, "PublicPropertyThrowsOnGet", true)]
#if NET7_0_OR_GREATER
[InlineData(false, "PublicRequiredProperty", false)]
#endif
[Theory]
public void DefaultTests(bool preserveSetValue, string propertyName, bool expected)
{
var finder = new DefaultPropertySelector(preserveSetValue);

var instance = new HasProperties();
var instance = new HasProperties
{
#if NET7_0_OR_GREATER
PublicRequiredProperty = new(),
#endif
};
var property = instance.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

Assert.Equal(expected, finder.InjectProperty(property, instance));
Expand Down Expand Up @@ -53,6 +61,10 @@ public Test PublicPropertyThrowsOnGet
}
}

#if NET7_0_OR_GREATER
required public Test PublicRequiredProperty { get; set; }
#endif

public Test PublicPropertyWithDefault { get; set; } = new Test();

private Test PrivatePropertyWithDefault { get; set; } = new Test();
Expand Down

0 comments on commit 1910177

Please sign in to comment.