nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
66.9k stars 7.55k forks source link

NestJs DI `useFactory` ignores property dependencies #13411

Closed Woodz closed 5 months ago

Woodz commented 5 months ago

Is there an existing issue for this?

Current behavior

Given a class that has both constructor and property dependencies, useFactory documentation, usage examples and typing only covers the constructor dependencies. This means that property dependencies are not automatically injecting, resulting in runtime errors and confusion

Minimum reproduction code

https://stackblitz.com/edit/nestjs-typescript-starter-kjzcnx?file=src%2Fapp.service.ts,src%2Fapp.module.ts

Steps to reproduce

No response

Expected behavior

Suggestions:

  1. Inject property dependencies when using useFactory
  2. clearly document that useFactory does not inject property dependencies (and somehow add type safety such that useFactory implementations that do not inject property dependencies are caught)
  3. Provide functionality in useFactory to allow property injection to be controlled (e.g. add optional 2nd parameter that is a property injection callback that can override default property injection)

Package

Other package

No response

NestJS version

No response

Packages versions

See repo

Node.js version

No response

In which operating systems have you tested?

Other

Use case: I have a class that has constructor parameters that I need to manually control (hence why I am using useFactory) but also has injected properties dynamically added by Typescript decorators. I want the injected properties to be automatically resolved, but the constructor parameters to be manually controlled. For now, I am working around by manually setting the properties in the useFactory but this is not type safe or scalable (since property dependencies are dynamic based on decorator usage)

kamilmysliwiec commented 5 months ago

IMO this should be obvious(?). You're instantiating a class yourself (without the framework controlling and orchestrating this process), meaning, you can't expect the framework to run another extra check on every custom provider just to verify if there are any extra operations to be performed.

This is the expected behavior of the framework but if you think it should be further explained & highlighted in the documentation, then please, create a PR to the docs (contributions are more than welcome)!