Skip to content

Constructor selection strategy in GetConstructorAndParameters diverges from ActivatorUtilities #23

Description

@AGiorgetti

Description

GetConstructorAndParameters in ServiceCollectionExtensions.KeyedService.cs always selects the constructor with the most parameters:

ctor = target.GetConstructors()
    .OrderByDescending(c => c.GetParameters().Length)
    .First();

This does not match ActivatorUtilities.CreateInstance semantics, which considers which constructor can be best satisfied by the available services. If a type has a constructor with more parameters but not all are resolvable, this will silently select the wrong constructor and fail at runtime.

Suggestion

Consider either:

  1. Aligning the behavior with ActivatorUtilities (use ActivatorUtilities.CreateFactory or similar)
  2. Adding prominent XML documentation warning about this divergence
  3. Validating that all constructor parameters can be satisfied by the dependsOn array + registered services

The existing comment acknowledges this: // maybe we should use the same strategy of: ActivatorUtilities.CreateInstance

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions