ASP.NET Core Dependency Injection with Multiple Constructors

Apply the ActivatorUtilitiesConstructorAttribute to the constructor that you want to be used by DI:

[ActivatorUtilitiesConstructor]
public MyClass(ICustomDependency d)
{
}

This requires using the ActivatorUtilities class to create your MyClass. As of .NET Core 3.1 the Microsoft dependency injection framework internally uses ActivatorUtilities; in older versions you need to manually use it:

services.AddScoped(sp => ActivatorUtilities.CreateInstance<MyClass>(sp));

Leave a Comment