Why are constructor-based injections preferred over property-based injections in nestjs

Viewed 635

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?

2 Answers

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/

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

Related