Asp.net-core – ASP.NET Core Dependency Injection with Multiple Constructors

asp.netasp.net-coreasp.net-core-mvcdependency-injection

I have a tag helper with multiple constructors in my ASP.NET Core application. This causes the following error at runtime when ASP.NET 5 tries to resolve the type:

InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'MyNameSpace.MyTagHelper'. There should only be one applicable constructor.

One of the constructors is parameterless and the other has some arguments whose parameters are not registered types. I would like it to use the parameterless constructor.

Is there some way to get the ASP.NET 5 dependency injection framework to select a particular constructor? Usually this is done through the use of an attribute but I can't find anything.

My use case is that I'm trying to create a single class that is both a TagHelper, as well as a HTML helper which is totally possible if this problem is solved.

Best Answer

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));