Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Dependency Injection with Multiple Constructors

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.

like image 744
Muhammad Rehan Saeed Avatar asked Oct 04 '15 08:10

Muhammad Rehan Saeed


People also ask

Can a controller have multiple constructors?

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.

Can you have multiple constructors?

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.

Can you have multiple constructors in C#?

Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments.

What is constructor in ASP.NET Core?

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.


1 Answers

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)); 
like image 139
Mahdi Ataollahi Avatar answered Sep 18 '22 18:09

Mahdi Ataollahi