7

The nestjs docs describe two main approaches for injecting dependencies, constructor-based and property-based injection. It's also mentioned that constructor-based injections should be preferred over property-based injection where possible without any description why.

Is there any specific reason for this or is it just some kind of code style guide?

buddha
  • 141
  • 10

2 Answers2

3

Someone had asked the same thing on their discord but the answer isn't super clear... Here's a screenshot of the conversation: enter image description here

Gpack
  • 1,878
  • 3
  • 18
  • 45
-2

WARNING If your class doesn't extend another provider, you should always prefer using constructor-based injection.

The nestjs docs does mention the reason to always prefer constructor-based injection. It states that if your class doesn't extend another provider then we should always use constructor-based injection.

What this means is that if your class has optional dependencies then you can use property-based injection otherwise you have to use constructor-based injection.

Consider, Class A which depends on Class B and Class A will not work if Class B is not injected in this case this is a mandatory dependency hence we have to use constructor-based injection.

Whereas, same Class A also depends on Class C but Class A will still work if Class C is not injected in this case it is an optional dependency hence we can use property-based injection here.

You can read more about this here:

https://khalilstemmler.com/articles/tutorials/dependency-injection-inversion-explained/ http://dillonbuchanan.com/programming/dependency-injection-constructor-vs-property/

Rasool Khan
  • 413
  • 6
  • 15
  • 1
    But property-based injections are not optional in nestjs as far as I know? When I remove the provider of a property-based injection, the build fails as it would be with constructor-based injections. So I don't see a difference here. The docs rather describe an advantage of property-based injections, which is, you don't have to pass the dependencies to the parent constructor in sub classes. – buddha Dec 14 '21 at 09:59