Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lawrence-laz/33ad8aaf3bafa6c4a644ebbeb8ededdb to your computer and use it in GitHub Desktop.
Save lawrence-laz/33ad8aaf3bafa6c4a644ebbeb8ededdb to your computer and use it in GitHub Desktop.
Reproducing ActivatorUtilities.CreateInstance & ActivatorUtilitiesConstructorAttribute Bug
using Microsoft.Extensions.DependencyInjection;
using System;
using Xunit;
namespace UnitTests
{
public class ActivatorUtilitiesConstructorTests
{
public class Dependency1 { }
public class Dependency2 { }
public class Dependency3 { }
public class Service1
{
public Service1(Dependency1 dependency1, Dependency3 dependency3)
{
throw new Exception("This should not be called.");
}
[ActivatorUtilitiesConstructor]
public Service1(Dependency1 dependency1, Dependency2 dependency2, Dependency3 dependency3)
{
}
}
public class Service2
{
[ActivatorUtilitiesConstructor]
public Service2(Dependency1 dependency1, Dependency2 dependency2, Dependency3 dependency3)
{
}
public Service2(Dependency1 dependency1, Dependency3 dependency3)
{
throw new Exception("This should not be called.");
}
}
[Fact]
public void CreateInstance_WithActivatorUtilitiesConstructorBeingSecond_ShouldChooseMarkedCtor()
{
// Arrange
var dependency1 = new Dependency1();
var dependency3 = new Dependency3();
var provider = new ServiceCollection()
.AddScoped<Dependency2>()
.BuildServiceProvider();
// Act & Assert
ActivatorUtilities.CreateInstance<Service1>(provider, dependency1, dependency3); // This works.
}
[Fact]
public void CreateInstance_WithActivatorUtilitiesConstructorBeingFirst_ShouldChooseMarkedCtor()
{
// Arrange
var dependency1 = new Dependency1();
var dependency3 = new Dependency3();
var provider = new ServiceCollection()
.AddScoped<Dependency2>()
.BuildServiceProvider();
// Act & Assert
ActivatorUtilities.CreateInstance<Service2>(provider, dependency1, dependency3); // This fails.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment