Muhammad Rehan Saeed Muhammad Rehan Saeed - 1 year ago 377
ASP.NET (C#) Question

ASP.NET 5 MVC 6 Dependency Injection with Multiple Constructors

I have a tag helper with multiple constructors in my ASP.NET 5 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.

Answer Source

Illya is right: the built-in resolver doesn't support types exposing multiple constructors... but nothing prevents you from registering a delegate to support this scenario:

services.AddScoped<IService>(provider => {
    var dependency = provider.GetRequiredService<IDependency>();

    // You can select the constructor you want here.
    return new Service(dependency, "my string parameter");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download