ASP.NET Core Dependency Injection with Multiple Constructors ASP.NET Core Dependency Injection with Multiple Constructors asp.net asp.net

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


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

Note: support for multiple constructors was added in later versions, as indicated in the other answers. Now, the DI stack will happily choose the constructor with the most parameters it can resolve. For instance, if you have 2 constructors - one with 3 parameters pointing to services and another one with 4 - it will prefer the one with 4 parameters.


ASP.NET Core 1.0 Answer

The other answers are still true for parameter-less constructors i.e. if you have a class with a parameter-less constructor and a constructor with arguments, the exception in the question will be thrown.

If you have two constructors with arguments, the behaviour is to use the first matching constructor where the parameters are known. You can look at the source code for the ConstructorMatcher class for details here.