0

I am using Asp .net core 2.2 with built-in DI. I want to inject service that has multiple constructors that fulfill the container conditions. And I can't remove the other constructor for backward compatibility. Example code:

public interface IService{
   void DoSomthing();
}

public class Implementation : IService
{
    public Implementation(IService1 service1)
    {

    }

    public Implementation(IService1 service1, IService2 service2)
    {

    }

    public void DoSomthing()
    {
        // Do something
    }
}

I registered all these services in the DI container example:

services.AddScoped<IService, Implementation>();

Now I have another class that uses IService as DI:

public class ClassA : IService
{
    public ClassA(IService service)
    {

    }
}

How Dependency injection container will intialize this class using which constructor?:

public Implementation(IService1 service1)
Or
public Implementation(IService1 service1, IService2 service2)

and what is the rule for choosing between them?

Husam Zidan
  • 619
  • 6
  • 18

1 Answers1

1

If you only bind IService1 it will call the constructor that only takes IService1. If you also bind IService2, it will call the constructor with IService2. If you have a class (like your ClassA) that only has one constructor that only takes an IService1, it will call that constructor regardless of whether you've bound an IService2.

rory.ap
  • 34,009
  • 10
  • 83
  • 174