1

I'm working on a .NetCore Web API project.
The project uses Depencency Injection. Each controller leverages constructor injection to get dependencies.
As the features grow, the code level dependencies grow and become complex to manage in terms of code quality(e.g. SonarQube, where maximum parameters are limited to 7).

Why is constructor injection preferred?
What about just injecting IServiceProvider and using GetServices<T>()?

the-petrolhead
  • 597
  • 1
  • 5
  • 16

2 Answers2

2

Complete books are written on this topic, but in short:

  • Letting application code directly resolve dependencies from the container is a form of Service Location, which is considered by many to be an anti-pattern, because of its downsides. This article goes into more detail about its downsides.
  • Reverting to Service Locator from a constructor with many parameters is a bad idea, because this doesn't solve the root problem, which is that that class has too many dependencies. It's too big and is likely violating the Single Responsibility Principle. Having many constructor arguments is a code smell, which is named: Constructor Over-Injection.
Steven
  • 166,672
  • 24
  • 332
  • 435
-1

In this case you should use a interface, it's better than calling the service directily. Why? Because the interface is the sign of the class and give you a structure of all your class and perform your RAM.

Example:

1-You should create a Interface:

public interface Iexample{
   string AddPerson
}

2-You should have a database instance in your service.

public class Example:Iexample
{
   private readonly Iexample _DBContext
    
   public Example(Iexample dbContext ){
     _DBContext=dbContext;
   }

}

3-You have to create the same method like the interface and all going to be ready.

public class Example:Iexample{
   private readonly Iexample _DBContext
    
   public Example(Iexample dbContext ){
     _DBContext=dbContext;
   }

   public string GetAll(string code)
      return code;
   }
}
Fabio Mendes Soares
  • 1,357
  • 5
  • 20
  • 30