From a47b1d7a8d83f9c46e955c9be99badd691929016 Mon Sep 17 00:00:00 2001 From: alistairjevans Date: Wed, 28 Aug 2019 17:41:30 +0100 Subject: [PATCH] Added test and fix to prevent Autofac injecting onto static properties --- .../Reflection/AutowiringPropertyInjector.cs | 7 +++++++ .../PropertyInjection/HasStaticSetter.cs | 9 +++++++++ .../Features/PropertyInjectionTests.cs | 20 +++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 test/Autofac.Specification.Test/Features/PropertyInjection/HasStaticSetter.cs diff --git a/src/Autofac/Core/Activators/Reflection/AutowiringPropertyInjector.cs b/src/Autofac/Core/Activators/Reflection/AutowiringPropertyInjector.cs index ecaf56311..c32300380 100644 --- a/src/Autofac/Core/Activators/Reflection/AutowiringPropertyInjector.cs +++ b/src/Autofac/Core/Activators/Reflection/AutowiringPropertyInjector.cs @@ -110,6 +110,13 @@ private static IEnumerable GetInjectableProperties(Type instanceTy continue; } + // SetMethod will be non-null if CanWrite is true. + // Don't want to inject onto static properties. + if (property.SetMethod.IsStatic) + { + continue; + } + var propertyType = property.PropertyType; if (propertyType.GetTypeInfo().IsValueType && !propertyType.GetTypeInfo().IsEnum) diff --git a/test/Autofac.Specification.Test/Features/PropertyInjection/HasStaticSetter.cs b/test/Autofac.Specification.Test/Features/PropertyInjection/HasStaticSetter.cs new file mode 100644 index 000000000..e66981da6 --- /dev/null +++ b/test/Autofac.Specification.Test/Features/PropertyInjection/HasStaticSetter.cs @@ -0,0 +1,9 @@ +using System; + +namespace Autofac.Specification.Test.Features.PropertyInjection +{ + public class HasStaticSetter + { + public static string Val { get; set; } + } +} diff --git a/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs b/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs index 8ff3930b0..28269d725 100644 --- a/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs +++ b/test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs @@ -178,6 +178,26 @@ public void PropertiesAutowiredDoesNotSetNonPublicSetter() Assert.Equal("Default", instance.Val); } + [Fact] + public void PropertiesAutowiredDoesNotSetStaticSetter() + { + var val = "Value"; + + // Clear it out before the test runs + HasStaticSetter.Val = null; + + var builder = new ContainerBuilder(); + builder.RegisterInstance(val); + builder.RegisterType().PropertiesAutowired(); + + var container = builder.Build(); + + var instance = container.Resolve(); + + Assert.NotNull(instance); + Assert.Null(HasStaticSetter.Val); + } + [Fact] public void PropertiesAutowiredOverwritesSetProperties() {