Skip to content

Added test and fix to prevent Autofac injecting onto static properties #1021

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ private static IEnumerable<PropertyInfo> 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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System;

namespace Autofac.Specification.Test.Features.PropertyInjection
{
public class HasStaticSetter
{
public static string Val { get; set; }
}
}
20 changes: 20 additions & 0 deletions test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HasStaticSetter>().PropertiesAutowired();

var container = builder.Build();

var instance = container.Resolve<HasStaticSetter>();

Assert.NotNull(instance);
Assert.Null(HasStaticSetter.Val);
}

[Fact]
public void PropertiesAutowiredOverwritesSetProperties()
{
Expand Down