Skip to content

Commit

Permalink
Add test for parameterless ctor dotnet#45119
Browse files Browse the repository at this point in the history
Calling `ActivatorUtilities.CreateInstance` without additional arguments
should prefer parameterless constructor as there are no guarantees that
parameters, for which arguments were not supplied, can be resolved from
the ServiceProvider.
  • Loading branch information
lawrence-laz committed Apr 3, 2021
1 parent 90e0dfd commit d186769
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,22 @@ public void TypeActivatorCreateInstanceUsesMarkedConstructor(int argument1, stri
Assert.Equal(ctor, ((ClassWithAmbiguousCtorsAndAttributeFirst)instance).CtorUsed);
}

[Fact]
public void TypeActivatorCreateInstanceUsesParameterlessConstructor()
{
// Arrange
var serviceCollection = new TestServiceCollection();
serviceCollection.AddSingleton<IFakeService, FakeService>();
var serviceProvider = CreateServiceProvider(serviceCollection);
var type = typeof(ClassWithParameterlessCtor);

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

// Assert
Assert.Equal("Parameterless", ((ClassWithParameterlessCtor)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,20 @@
// 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 ClassWithParameterlessCtor
{
public ClassWithParameterlessCtor(IFakeService dependency)
{
CtorUsed = "IFakeService";
}

public ClassWithParameterlessCtor()
{
CtorUsed = "Parameterless";
}

public string CtorUsed { get; set; }
}
}

0 comments on commit d186769

Please sign in to comment.