Skip to content

fix(core): discover factory providers with discovery decorators - #17667

Merged
kamilmysliwiec merged 1 commit into
nestjs:masterfrom
hktitof:fix/discovery-factory-providers
Sep 14, 2026
Merged

kamilmysliwiec merged 1 commit into
nestjs:masterfrom
hktitof:fix/discovery-factory-providers

Conversation

@hktitof

@hktitof hktitof commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

a provider registered via useFactory is never returned by discoveryService.getProviders({ metadataKey }) when the factory returns a class decorated with a custom DiscoveryService decorator, the same class registered as a plain provider (useClass) is returned fine

bcs the discovery meta host inspection runs once at registration time (Container.addProvider) and a factory provider has no instance yet at that point, so the lookup keys on the factory function instead of the decorated class, and nothing inspects the wrapper again after the instance is created

this is the same gap #17617 reported for useValue, fixed by #17618, whose own comment says factory providers should resolve through wrapper.instance.constructor too — that intent is unreachable today bcs the inspection never re-runs post-instantiation

Issue Number: N/A

Steps to reproduce

  1. run npx vitest run packages/core/test/discovery/discovery-service.spec.ts on untouched master (the spec "should discover a provider decorated with a discovery decorator")
  2. Expected: the decorated provider registered via useFactory is discovered like its useClass sibling
  3. Actual (raw output on untouched master, fix stashed):
 FAIL  packages/core/test/discovery/discovery-service.spec.ts > Discovery of providers registered via useFactory > should discover a provider decorated with a discovery decorator
AssertionError: expected [] to have a length of 1 but got +0

- Expected
+ Received

- 1
+ 0

 ❯ packages/core/test/discovery/discovery-service.spec.ts:601:23
    599|       .getProviders({ metadataKey: TestDecorator.KEY });
    600|
    601|     expect(providers).toHaveLength(1);
    602|     expect(providers[0].instance).toBeInstanceOf(FactoryService);
    603|

      Tests  1 failed | 28 passed (29)

What is the new behavior?

InstanceLoader.createInstancesOfProviders now re-inspects each provider wrapper right after its instance is created, so useFactory behaves the same as useClass and useValue, and a decorated class is discoverable no matter which registration style delivered it

i kept the registration-time inspection in place and the re-insertion is a Set add, so wrappers already registered are untouched and nothing gets duplicated, and the lookup stays keyed under the same modules container the registration path uses (lazy loading included)

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

tested with:

  • npx vitest run packages/core/test/discovery/discovery-service.spec.ts -> 29 passed, and the new spec fails on untouched master without the fix (raw output above)
  • npm run test -> 2790 passed, 1 failure in packages/common/test/services/logger.service.spec.ts that also fails on clean master, unrelated
  • npx prettier --check and npx oxlint on the touched files -> clean

@hktitof
hktitof force-pushed the fix/discovery-factory-providers branch from 4cf4a42 to aed2271 Compare September 4, 2026 07:38
@hktitof
hktitof force-pushed the fix/discovery-factory-providers branch from aed2271 to 2ded04c Compare September 11, 2026 13:38

@micalevisk micalevisk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough write-up, the diagnosis is accurate and I could reproduce both the failure on master and the fix. One behavior change needs handling before this can go in, plus a couple of test gaps.

What checks out

  • Registration-time inspection keys a factory wrapper on the factory function and nothing re-inspects after instantiation, exactly as described.
  • The dedupe-by-id in insertByMetaKey is necessary. Injector.loadPrototype replaces every newable (useClass) wrapper with a copy that keeps the same id (the id symbol is spread into the new wrapper). Without that loop, each decorated useClass provider is returned twice after this change. Verified locally.
  • Side benefit: discovered wrappers are now the same objects held in module.providers. On master they are the stale pre-prototype copies, which only works because both share the values map.
  • Lazy-loaded modules are covered: a decorated factory provider in a lazily loaded module is discovered with this PR and not on master.

Requested change

useExisting aliases now show up as discovered providers. An alias wrapper is factory-shaped (metatype: instance => instance, inject: [useExisting]), so after instantiation instance.constructor resolves to the decorated class and the alias gets inserted too.

Repro: register Aliased (decorated) plus { provide: 'ALIAS', useExisting: Aliased }. On master getProviders({ metadataKey }) returns 1 wrapper. With this PR it returns 2, both pointing at the same instance. Any consumer iterating discovered providers will process the same object twice. The codebase already treats aliases as non-providers elsewhere (Module#getNonAliasProviders), so I'd skip them here:

if (!item.isAlias) {
  DiscoverableMetaHostCollection.inspectProvider(
    this.container.getModules(),
    item,
  );
}

Test gaps

  • The dedupe loop is untested. The new spec only registers a factory provider, which never goes through the prototype copy, so deleting the loop leaves the spec green. Please add a spec that bootstraps a decorated useClass provider and asserts exactly one result (and ideally a unit test in discoverable-meta-host-collection.spec.ts for the same-id replacement).
  • A spec for the useExisting case above once it's guarded.

Optional / nits

  • Alternative design: re-inspect only factory-shaped wrappers (item.isFactory && !item.isAlias). Factory and value wrappers are never copied by loadPrototype, so Set.add dedupes by identity and the id loop becomes unnecessary. You'd lose the "module-held wrapper" side benefit, so either is defensible; just flagging it.
  • Request-scoped useFactory providers still aren't discovered (no static instance to inspect), while request-scoped useClass ones are. Not a regression, but worth a line in the description.
  • In the new spec, compile() already instantiates providers, so createNestApplication() + app.init() aren't needed; moduleRef.get(DiscoveryService) is enough.
  • The new describe block sits outside the existing describe('DiscoveryService'), unlike the rest of the file.

DiscoveryService.getProviders({ metadataKey }) misses providers registered
via useFactory when the factory returns a class decorated with a custom
discovery decorator

bcs providers get inspected for the discovery meta host at registration time,
and a factory provider has no instance yet at that point, so the lookup keys
on the factory function instead of the decorated class, and the inspection
never runs again after the instance is created

this re-inspects providers in InstanceLoader right after their instances are
created, so useFactory behaves the same as useClass and useValue. inserts are
keyed by the wrapper instance id (the prototype phase replaces the map entry
with a copy sharing it), and alias wrappers are skipped, bcs an alias is
factory-shaped too and inspecting it would discover the aliased provider
twice, same non-provider treatment as Module#getNonAliasProviders

specs pin the useFactory discovery, the single-entry useClass case after the
prototype copy, the useExisting case and the same-id replacement itself
@hktitof
hktitof force-pushed the fix/discovery-factory-providers branch from 2ded04c to 4450e5e Compare September 13, 2026 01:02
@hktitof

hktitof commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

thanks for the review and the verified repro @micalevisk, the alias double-count was a real one. the isAlias guard is in exactly like your snippet, plus the useClass single-entry spec, the useExisting spec and the same-id dedupe unit test, 49 discovery tests green on the touched suites

@kamilmysliwiec
kamilmysliwiec merged commit 1d1dbf7 into nestjs:master Sep 14, 2026
3 checks passed
@kamilmysliwiec

Copy link
Copy Markdown
Member

lgtm

ttt43ttt pushed a commit to NoDevelopers/ts-monorepo that referenced this pull request Nov 22, 2026
| datasource | package                  | from   | to     |
| ---------- | ------------------------ | ------ | ------ |
| npm        | @nestjs/common           | 12.0.1 | 12.1.0 |
| npm        | @nestjs/core             | 12.0.1 | 12.1.0 |
| npm        | @nestjs/platform-express | 12.0.1 | 12.1.0 |


## [v12.1.0](https://github.com/nestjs/nest/releases/tag/v12.1.0)

##### v12.1.0 (2026-09-23)

##### Bug fixes

- `core`
  - [#17838](nestjs/nest#17838) fix(core): inherit optional ctor params when the ctor is not redeclared ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17819](nestjs/nest#17819) fix(core): name the module when metadata entries are invalid ([@thekhegay](https://github.com/thekhegay))
- `microservices`
  - [#17828](nestjs/nest#17828) fix(microservices): let the redis client retry after a failed connect ([@hktitof](https://github.com/hktitof))
  - [#17810](nestjs/nest#17810) fix(microservices): fail every pending request when a callback throws ([@hktitof](https://github.com/hktitof))

##### Enhancements

- `core`
  - [#17846](nestjs/nest#17846) fix(core): do not skip subsequent middleware after a transient one ([@lehafari](https://github.com/lehafari))
  - [#17840](nestjs/nest#17840) fix(core): preserve route handler names ([@Grmiade](https://github.com/Grmiade))
- `common`, `core`
  - [#17713](nestjs/nest#17713) feat(core): add support for array of global prefixes ([@micalevisk](https://github.com/micalevisk))
  - [#17834](nestjs/nest#17834) feat(common,core): add built-in, adapter-agnostic cookies ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `platform-fastify`
  - [#17824](nestjs/nest#17824) fix(fastify): honor Nest forceCloseConnections in initHttpServer ([@xia-chao](https://github.com/xia-chao))
- `common`
  - [#17827](nestjs/nest#17827) fix(common): apply the ParseDatePipe default to every missing value ([@xia-chao](https://github.com/xia-chao))
- `platform-fastify`, `testing`
  - [#17835](nestjs/nest#17835) feat(fastify): add file upload interceptors backed by [@fastify/multipart](https://github.com/fastify/multipart) ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`, `core`, `platform-fastify`
  - [#17836](nestjs/nest#17836) feat(common,core,fastify): built-in CSRF protection and security headers ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Committers: 9

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Alejandro ([@lehafari](https://github.com/lehafari))
- Chris Z ([@haimingZZ](https://github.com/haimingZZ))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Jérémy Fauvel ([@Grmiade](https://github.com/Grmiade))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk))
- Roman Khegay ([@thekhegay](https://github.com/thekhegay))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))


## [v12.0.4](https://github.com/nestjs/nest/releases/tag/v12.0.4)

##### v12.0.4 (2026-09-21)

##### Bug fixes

- `microservices`
  - [#17816](nestjs/nest#17816) fix(microservices): let the kafka client retry after a failed connect ([@Xch4rt](https://github.com/Xch4rt))
  - [#17786](nestjs/nest#17786) fix(microservices): fail pending rmq requests on client close ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
  - [#17802](nestjs/nest#17802) fix(microservices): fail pending nats requests on client close ([@hktitof](https://github.com/hktitof))
  - [#17803](nestjs/nest#17803) fix(microservices): handle missing grpc package namespace gracefully ([@Se3do](https://github.com/Se3do))
  - [#17799](nestjs/nest#17799) fix(microservices): share the processing hook envelope across transports ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17797](nestjs/nest#17797) fix(microservices): close the kafka request-response span exactly once ([@MingLin1995](https://github.com/MingLin1995))
  - [#17794](nestjs/nest#17794) fix(microservices): close the request-response span exactly once ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17785](nestjs/nest#17785) fix(microservices): route message handler rejections to handleError ([@hktitof](https://github.com/hktitof))
- `core`
  - [#17821](nestjs/nest#17821) fix(core): hang on sparse factory inject array ([@xia-chao](https://github.com/xia-chao))

##### Enhancements

- `platform-express`
  - [#17818](nestjs/nest#17818) Fix: merge multer `limits` key-by-key instead of overriding it wholesale ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy))
- `common`
  - [#17780](nestjs/nest#17780) fix(common): mark parse date pipe options as optional ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid))

##### Dependencies

- `common`
  - [#17793](nestjs/nest#17793) fix(deps): update dependency file-type to v22.1.1 ([@renovate\[bot\]](https://github.com/apps/renovate))
- `platform-fastify`
  - [#17791](nestjs/nest#17791) fix(deps): update dependency fastify to v5.12.5 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 10

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Chowdhury Zaber Bin Zahid ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid))
- Imad - Prakticode ([@prakticode](https://github.com/prakticode))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- MD. Ridoy Babu ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy))
- Ming ([@MingLin1995](https://github.com/MingLin1995))
- Mohammed Said ([@Se3do](https://github.com/Se3do))
- Pablo Gutiérrez ([@Xch4rt](https://github.com/Xch4rt))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))


## [v12.0.3](https://github.com/nestjs/nest/releases/tag/v12.0.3)

##### v12.0.3 (2026-09-15)

##### Bug fixes

- `microservices`
  - [#17766](nestjs/nest#17766) fix(microservices): always run the kafka processing end hook ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17757](nestjs/nest#17757) fix(microservices): fail pending requests on client close ([@hktitof](https://github.com/hktitof))
  - [#17746](nestjs/nest#17746) fix(microservices): bound memory held for a TCP peer ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17745](nestjs/nest#17745) fix(microservices): destroy open TCP sockets on shutdown ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`
  - [#17738](nestjs/nest#17738) fix(common): validate uuid version and variant when no version is set ([@otnc](https://github.com/otnc))
  - [#17761](nestjs/nest#17761) fix(common): invoke proto-key stripping hook via this in transform ([@koreahghg](https://github.com/koreahghg))

##### Dependencies

- `platform-express`
  - [#17762](nestjs/nest#17762) fix(deps): update dependency multer to v2.4.0 ([@renovate\[bot\]](https://github.com/apps/renovate))
- `common`
  - [#17753](nestjs/nest#17753) fix(deps): update dependency file-type to v22.1.0 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 4

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- otoneko. ([@otnc](https://github.com/otnc))
- 한국 ([@koreahghg](https://github.com/koreahghg))


## [v12.0.2](https://github.com/nestjs/nest/releases/tag/v12.0.2)

##### v12.0.2 (2026-09-14)

##### Bug fixes

- `platform-socket.io`, `platform-ws`
  - [#17666](nestjs/nest#17666) fix(socket.io): keep the message stream alive when a handler throws ([@hktitof](https://github.com/hktitof))
- `microservices`
  - [#17728](nestjs/nest#17728) fix(microservices): detach signal listeners of connected microservices ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#17671](nestjs/nest#17671) fix(microservices): fail requests whose reply subscription is rejected ([@samuelmbabhazi](https://github.com/samuelmbabhazi))
  - [#17670](nestjs/nest#17670) fix(microservices): do not treat foreign JSON as an RPC envelope ([@xia-chao](https://github.com/xia-chao))
  - [#17644](nestjs/nest#17644) fix(microservices): don't flatten plain handler results with pre-request hooks ([@iamolegga](https://github.com/iamolegga))
  - [#17641](nestjs/nest#17641) fix(microservices): run the mqtt listen callback once ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- `common`
  - [#17710](nestjs/nest#17710) fix(common): collapse duplicate internal slashes in `normalizePath` ([@Asadshah7950](https://github.com/Asadshah7950))
  - [#17655](nestjs/nest#17655) fix(common): validate UUID v3 variant ([@gwagjiug](https://github.com/gwagjiug))
  - [#17702](nestjs/nest#17702) fix(common): treat empty string as array input in ParseArrayPipe ([@xia-chao](https://github.com/xia-chao))
- `core`
  - [#17667](nestjs/nest#17667) fix(core): discover factory providers with discovery decorators ([@hktitof](https://github.com/hktitof))
  - [#17709](nestjs/nest#17709) fix(core): avoid treating error instances with `statusCode` as http errors ([@Asadshah7950](https://github.com/Asadshah7950))
  - [#17625](nestjs/nest#17625) fix(core): clean up repeated shutdown signal listeners ([@Raj4478](https://github.com/Raj4478))
- `platform-fastify`
  - [#17705](nestjs/nest#17705) fix(fastify): derive neutral version when accept header is absent ([@Gaurav1112](https://github.com/Gaurav1112))
  - [#17699](nestjs/nest#17699) fix(fastify): send responses for exceptions thrown from middleware ([@micalevisk](https://github.com/micalevisk))

##### Enhancements

- `microservices`
  - [#17734](nestjs/nest#17734) feat(microservices): add maxConnectionAttempts to ServerMqtt ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Dependencies

- `platform-fastify`
  - [#17729](nestjs/nest#17729) fix(deps): update dependency fastify to v5.12.4 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 16

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Alexey Solovyov ([@lyohaplotinka](https://github.com/lyohaplotinka))
- Asad Ali Shah ([@Asadshah7950](https://github.com/Asadshah7950))
- Gyeonghun Park ([@Gyeonghun-Park](https://github.com/Gyeonghun-Park))
- Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Kumar Gaurav ([@Gaurav1112](https://github.com/Gaurav1112))
- Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk))
- Ming ([@MingLin1995](https://github.com/MingLin1995))
- Mohammed Said ([@Se3do](https://github.com/Se3do))
- Rajeshwar Singh  ([@Raj4478](https://github.com/Raj4478))
- Xia Chao ([@xia-chao](https://github.com/xia-chao))
- [@iamolegga](https://github.com/iamolegga)
- cui fliter ([@cuishuang](https://github.com/cuishuang))
- samuel mbabhazi ([@samuelmbabhazi](https://github.com/samuelmbabhazi))
- 곽지욱 ([@gwagjiug](https://github.com/gwagjiug))
@hktitof

hktitof commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review and merge @kamilmysliwiec, glad this fix is in now, cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants