Skip to content

fix(common,core): scope inject ctor params to the constructor owner - #18599

Closed
MrSatan wants to merge 1 commit into
nestjs:masterfrom
MrSatan:fix/inject-ctor-metadata-inheritance
Closed

MrSatan wants to merge 1 commit into
nestjs:masterfrom
MrSatan:fix/inject-ctor-metadata-inheritance

Conversation

@MrSatan

@MrSatan MrSatan commented Nov 19, 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?

Background & Context

This PR follows up on @kamilmysliwiec's work and design for constructor parameter metadata inheritance across class hierarchies:

  1. Initial fix for @Optional() (011bff6601 / Remove optional dependency metadata inherited from base class #2581): @kamilmysliwiec updated @Optional() and Injector#reflectOptionalParams() to read OPTIONAL_DEPS_METADATA with Reflect.getOwnMetadata() so that a subclass redeclaring its constructor does not inherit the parent's optional parameter indices.
  2. Follow-up constructor-owner resolution (ad1889073d / fix(core): inherit optional ctor params when the ctor is not redeclared #17838): @kamilmysliwiec followed up by introducing Injector#getConstructorOwner(type) so that a subclass without its own constructor (e.g., class LocalAuthGuard extends AuthGuard('local') {} or mixin subclasses) still inherits constructor metadata from the nearest class in the prototype chain that declares the constructor.
    Notably, when designing getConstructorOwner(), @kamilmysliwiec already included SELF_DECLARED_DEPS_METADATA as one of the three metadata keys identifying the constructor owner:
    if (
      Reflect.hasOwnMetadata(PARAMTYPES_METADATA, current) ||
      Reflect.hasOwnMetadata(OPTIONAL_DEPS_METADATA, current) ||
      Reflect.hasOwnMetadata(SELF_DECLARED_DEPS_METADATA, current)
    ) {
      return current;
    }
  3. Property injection follow-ups (fix(common): keep inherited @Optional() properties optional #17944 and fix(common): let a redeclared @Inject() property replace the parent's #17949): Property-based @Optional() and @Inject() inheritance (OPTIONAL_PROPERTY_DEPS_METADATA and PROPERTY_DEPS_METADATA) were subsequently aligned.

However, the constructor parameter branch of @Inject() (SELF_DECLARED_DEPS_METADATA) was missed in both places and still uses Reflect.getMetadata():

  • packages/common/decorators/core/inject.decorator.ts (line 52)
  • packages/core/injector/injector.ts in Injector#reflectSelfParams() (line 696)

Reproduction of the two failure modes

@Injectable()
class ParentService {
  constructor(@Inject('PARENT_TOKEN') a: unknown) {}
}

// Case 1: Subclass redeclares its constructor without @Inject()
@Injectable()
class ChildWithoutInjectService extends ParentService {
  constructor(private readonly myService: MyService) {
    super(myService);
  }
}

// Case 2: Subclass redeclares its constructor and uses @Inject() on another parameter
@Injectable()
class ChildWithInjectService extends ParentService {
  constructor(
    private readonly myService: MyService,
    @Inject('CHILD_TOKEN') b: unknown,
  ) {
    super(b);
  }
}
  • In Case 1: ChildWithoutInjectService has no own SELF_DECLARED_DEPS_METADATA. Injector#reflectSelfParams() calls Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, type), walks up the prototype chain to ParentService, and silently replaces parameter index 0 (MyService) with 'PARENT_TOKEN'. (Even an empty constructor() on the child ends up injecting 'PARENT_TOKEN' at index 0.)
  • In Case 2: When @Inject('CHILD_TOKEN') executes on ChildWithInjectService, inject.decorator.ts reads Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, target), copies { index: 0, param: 'PARENT_TOKEN' } from ParentService into the child's own metadata array, and appends { index: 1, param: 'CHILD_TOKEN' }. Again, parameter index 0 (MyService) is silently overwritten with 'PARENT_TOKEN'.

Issue Number: Related to #2581, #17838, #17949

What is the new behavior?

Completes @kamilmysliwiec's constructor-owner metadata design from 011bff6601 (#2581) and ad1889073d (#17838) for @Inject() constructor parameters:

  1. @Inject() (packages/common/decorators/core/inject.decorator.ts): Uses Reflect.getOwnMetadata(SELF_DECLARED_DEPS_METADATA, target) || [] in the parameter branch (!isUndefined(index)), matching @Optional() in optional.decorator.ts.
  2. Injector#reflectSelfParams() (packages/core/injector/injector.ts): Resolves SELF_DECLARED_DEPS_METADATA via Reflect.getOwnMetadata(SELF_DECLARED_DEPS_METADATA, this.getConstructorOwner(type)) || [], matching Injector#reflectOptionalParams().
    • When a subclass does not redeclare its constructor, getConstructorOwner(type) resolves to the parent class declaring the constructor, so the subclass continues to inherit the parent's @Inject() parameter tokens.
    • When a subclass does redeclare its constructor, getConstructorOwner(type) resolves to the subclass itself, so only the subclass's own @Inject() parameter tokens (if any) are used.

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Unit tests have been added in:

  • packages/common/test/decorators/inject.decorator.spec.ts (verifying @Inject() on a subclass constructor parameter does not copy the parent's SELF_DECLARED_DEPS_METADATA)
  • packages/core/test/injector/injector.spec.ts (mirroring @kamilmysliwiec's @Optional() inheritance test suite from fix(core): inherit optional ctor params when the ctor is not redeclared #17838 for both inherited constructors across ChildClass/GrandChildClass and redeclared constructors with @Inject(), without @Inject(), and with an empty constructor())

Since 011bff6 (nestjs#2581) and ad18890 (nestjs#17838), @optional() stores
constructor parameter metadata with getOwnMetadata and Injector reads
it from getConstructorOwner(type), while nestjs#17949 fixed redeclared
@Inject() properties. The constructor parameter branch of @Inject()
and Injector#reflectSelfParams() still used Reflect.getMetadata().

As a result, a subclass that redeclared its constructor without
@Inject() inherited the parent's SELF_DECLARED_DEPS_METADATA and had
its parameters silently replaced at matching indices. A subclass that
used @Inject() on its own constructor also copied the parent's entries
into its own metadata array.

Read SELF_DECLARED_DEPS_METADATA with getOwnMetadata in @Inject() and
from getConstructorOwner(type) in Injector#reflectSelfParams() so a
redeclared constructor uses only its own tokens while an inherited
constructor still keeps the parent's tokens.
@kamilmysliwiec

Copy link
Copy Markdown
Member

Thanks for digging into this. Reading @Inject() constructor metadata from the constructor owner is consistent with how @Optional() is read now, but it changes what gets injected into code that works today, so this can't go out in a patch or minor release.

A subclass that redeclares its constructor and relies on the parent's @Inject() token at the same position resolves on master:

@Injectable()
class Base {
  constructor(@Inject(CONFIG) readonly config: Config) {}
}

@Injectable()
class Child extends Base {
  constructor(
    config: Config,
    readonly other: Other,
  ) {
    super(config);
  }
}

With this PR, bootstrap fails with "Nest can't resolve dependencies of the Child (?, Other)". When the class at that position is itself a provider, the PR would inject that provider instead of the token, with no error at all.

The equivalent change for @Optional() landed in a major release (v12.0.0). Closing this for now; it's something to revisit for the next major.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants