The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method.
Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
Property Injection: In the property injection (aka the Setter Injection), the injector supplies the dependency through a public property of the client class.
Method Injection: In this type of injection, the client class implements an interface that declares the method(s) to supply the dependency and the injector uses this interface to supply the dependency to the client class.
When to use Property Dependency Injection over Constructor Injection and vice versa?
The Constructor Dependency Injection in C# is the standard for dependency injection. It ensures that all the dependency objects are initialized before we are going to invoke any methods or properties of the dependency object, as a result, it avoids the null reference exceptions.
The Setter/Property Dependency Injection in C# is rarely used in real-time applications. For example, if I have a class that has several methods but those methods do not depend on any other objects.
Now I need to create a new method within the same class but that new method now depends on another object. If we use the constructor dependency injection here, then we need to change all the existing constructor calls where we created this class object. This can be a very difficult task if the project is a big one. Hence, in such scenarios, the Setter or Property Dependency Injection can be a good choice.