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.
Don't use multiple constructors. Your classes should have a single definition of what dependencies it needs. That definition lies in the constructor and it should therefore only have 1 public constructor.
A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.
Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments.
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With