Skip to content

Commit

Permalink
Add test against ctor with attribute order dotnet#42339
Browse files Browse the repository at this point in the history
Using [ActivatorUtilitiesconstructor] attribute on a constructor should
force `ActivatorUtilities.CreateInstance` to use that constructor
regardless of the constructor definition order. This test shows that it
is not the case in current implementaion.
  • Loading branch information
lawrence-laz committed Apr 3, 2021
1 parent 4d26c31 commit 90e0dfd
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,23 @@ public void TypeActivatorCreateInstanceUsesFirstMathchedConstructor(object value
Assert.Equal(ctor, ((ClassWithAmbiguousCtors)instance).CtorUsed);
}

[Theory]
[InlineData(0, "", "int, IFakeService, string")]
public void TypeActivatorCreateInstanceUsesMarkedConstructor(int argument1, string argument2, string ctor)
{
// Arrange
var serviceCollection = new TestServiceCollection();
serviceCollection.AddSingleton<IFakeService, FakeService>();
var serviceProvider = CreateServiceProvider(serviceCollection);
var type = typeof(ClassWithAmbiguousCtorsAndAttributeFirst);

// Act
var instance = ActivatorUtilities.CreateInstance(serviceProvider, type, argument1, argument2);

// Assert
Assert.Equal(ctor, ((ClassWithAmbiguousCtorsAndAttributeFirst)instance).CtorUsed);
}

[Theory]
[MemberData(nameof(CreateInstanceFuncs))]
public void TypeActivatorUsesMarkedConstructor(CreateInstanceFunc createFunc)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.Extensions.DependencyInjection.Specification.Fakes
{
public class ClassWithAmbiguousCtorsAndAttributeFirst
{
[ActivatorUtilitiesConstructor]
public ClassWithAmbiguousCtorsAndAttributeFirst(int dependency1, IFakeService dependency2, string dependency3)
{
CtorUsed = "int, IFakeService, string";
}

public ClassWithAmbiguousCtorsAndAttributeFirst(int dependency1, string dependency3)
{
CtorUsed = "int, string";
}

public string CtorUsed { get; set; }
}
}

0 comments on commit 90e0dfd

Please sign in to comment.