Skip to content

C#: primary-constructor parameters are never walked, so constructor-injected dependencies produce no edges #2829

Closed

Description

@brobl2008

Summary

extract_csharp never walks a class's primary constructor parameter list, so
dependencies declared as class Foo(IBar bar) — the idiomatic C# 12 / .NET 8+ DI
pattern — are invisible to the graph. No references edge is emitted for the
parameter's type, and because the name is never registered as a class-scoped
receiver binding, every call through it (bar.Baz()) also loses its calls edge.

This is the C# twin of #2063 (Kotlin primary_constructor/class_parameters).
Scala already has the equivalent handling in the same file; C# never got it.

Not a duplicate of #2624. That issue is about explicit type arguments at a call
site (X.M<T>()) folding into the lookup key. The repro below contains no generics,
and #2676 states it "does not involve primary constructor parameter resolution."
The two also differ in severity — see the isolation table.

Root cause

Two C# member forms populate csharp_field_types and emit a references[field]
edge, in graphify/extractors/engine.py:

  • field_declaration → engine.py:3566 (records types at :3588, edge at :3608)
  • property_declaration → engine.py:3612 (records types at :3631)

There is no third branch for a class_declaration's parameter_list. Because
csharp_field_types[class_nid] is what _csharp_method_receiver_types
(engine.py:1609) takes as its field_types base scope, an unregistered name can
never be typed at a call site, so no calls edge is stamped either.

Note the tree-sitter shape — the parameter list is an unnamed child, so
child_by_field_name("parameters") returns None and the node must be found by
iterating children (exactly as the Scala class_parameters branch at engine.py:3426
already does):

>>> cls = parse(b"public class CaseA(IDep dep) { }").root_node.children[0]
>>> cls.type
'class_declaration'
>>> [c.type for c in cls.children]
['modifier', 'class', 'identifier', 'parameter_list', 'declaration_list']
>>> cls.child_by_field_name("parameters")
None

Each parameter child exposes the same name / type fields that
bind_parameter() (engine.py:1651) already consumes:

>>> [(p.child_by_field_name("name").text, p.child_by_field_name("type").text)
...  for p in parameter_list.children if p.type == "parameter"]
[(b'dep', b'IDep')]

Minimal reproduction

namespace Iso;

public interface IDep
{
    string Plain(int id);
    T Generic<T>(string key);
}

public class Dep : IDep
{
    public string Plain(int id) => "x";
    public T Generic<T>(string key) => default!;
}

// CASE A - primary constructor parameter
public class CaseA(IDep dep)
{
    public string Run(int id) => dep.Plain(id);
}

// CASE B - classic constructor + readonly field (control)
public class CaseB
{
    private readonly IDep _dep;
    public CaseB(IDep dep) { _dep = dep; }
    public string Run(int id) => _dep.Plain(id);
}

// CASE C - generic call site (#2624, for contrast)
public class CaseC
{
    private readonly IDep _dep;
    public CaseC(IDep dep) { _dep = dep; }
    public string Run() => _dep.Generic<string>("k");
}

// CASE D - local variable (control)
public class CaseD
{
    public string Run(int id)
    {
        var dep = new Dep();
        return dep.Plain(id);
    }
}
$ graphify extract ./src --code-only --force
$ graphify affected "IDep"

Affected nodes for IDep
- CaseB [references] Cases.cs:L24
- CaseC [references] Cases.cs:L32
- Dep   [implements] Cases.cs:L9
- .Run() [calls]     Cases.cs:L26
Case Pattern calls edge ref to IDep found by affected
A class CaseA(IDep dep) → dep.Plain(id) ✗ ✗ ✗ invisible
B ctor + field → _dep.Plain(id) ✓ ✓ ✓
C field → _dep.Generic<string>("k") ✗ (#2624) ✓ ✓
D local new Dep() → dep.Plain(id) ✓ n/a n/a

Case B is the control and passes, so constructor injection generally is fine —
it is primary constructors specifically that are dropped.

The severity difference against #2624 is the last column: Case C loses the calls
edge but keeps references[field], so the class is still discoverable by
affected. Case A has no edge of any kind and disappears from impact analysis
entirely — affected returns a confident, short, wrong answer rather than an error.

Positional record parameters are affected identically:

public record RecCase(IDep Dep)          // no edge to IDep
{
    public string Run(int id) => Dep.Plain(id);
}

Impact

Every class using this DI pattern loses its dependency edges entirely, and none of them
are reachable via affected on the interface they depend on. The losses concentrate on
service and data-access classes — the nodes impact-analysis traversals care about most.

Since C# 12 made primary constructors available to plain classes and not just records,
they are increasingly the default in new .NET code, so this affects a growing share of
C# graphs. A codebase that adopts the pattern as a documented convention loses its DI
edges wholesale.

Suggested fix

Add a class_declaration / record_declaration branch alongside the existing
field_declaration and property_declaration handlers that, for each parameter
in the unnamed parameter_list child:

  1. records name → type into csharp_field_types[class_nid], so the existing
    _csharp_method_receiver_types scoping resolves calls through it; and
  2. emits a references edge with context="field", matching engine.py:3608.

That mirrors #2063's Kotlin fix and the Scala class_parameters branch already at
engine.py:3426. Happy to open a PR if the approach looks right.

Tested on graphifyy 0.9.45, Python 3.14, macOS (arm64).

Activity

  1. brobl2008 commented on Aug 17, 2026

    @brobl2008
    ContributorAuthor

    I put together a patch for this and verified it locally — sharing the diff here rather than
    opening a PR, since #2063 (the Kotlin twin) is still awaiting review and I didn't want to add
    noise to the queue. Happy to turn it into a PR if that's useful.

    Against v8 @ 0738af3, +53 lines in one file, placed directly after the Scala
    class_parameters branch it mirrors:

    graphify/extractors/engine.py (+53)
    @@ -3441,6 +3441,59 @@ def _extract_generic(
                                     add_edge(class_nid, target_nid, "references",
                                              cp_line, context=ctx)
     
    +            # C#: a primary constructor (`class Foo(IBar bar)`, C# 12+) declares
    +            # its dependencies on the type declaration itself rather than in a
    +            # field or property, so neither the field_declaration nor the
    +            # property_declaration handler ever sees them — the parameter type
    +            # got no references edge, and because the name was never registered
    +            # in csharp_field_types, _csharp_method_receiver_types could not type
    +            # the receiver either, so calls through it (`bar.Baz()`) lost their
    +            # calls edge as well. The Scala class_parameters branch directly
    +            # above is the analogue; Kotlin's is #2063. Grammar note: the list is
    +            # an UNNAMED child of the declaration, so child_by_field_name(
    +            # "parameters") returns None and the children must be scanned.
    +            if config.ts_module == "tree_sitter_c_sharp" and t in (
    +                "class_declaration",
    +                "record_declaration",
    +                "struct_declaration",
    +            ):
    +                csharp_type_params = _csharp_type_parameters_in_scope(node, source)
    +                for c in node.children:
    +                    if c.type != "parameter_list":
    +                        continue
    +                    for param in c.children:
    +                        if param.type != "parameter":
    +                            continue
    +                        ptype = param.child_by_field_name("type")
    +                        if ptype is None:
    +                            continue
    +                        pname = param.child_by_field_name("name")
    +                        p_line = param.start_point[0] + 1
    +                        # Receiver binding mirrors the field_declaration rule:
    +                        # Pascal-case only (a primitive owns no resolvable
    +                        # method) and never a bare type parameter (`T item`).
    +                        recv = _csharp_receiver_type_name(ptype, source)
    +                        if (pname is not None and recv and recv[:1].isupper()
    +                                and recv not in csharp_type_params):
    +                            csharp_field_types.setdefault(class_nid, {})[
    +                                _read_text(pname, source)
    +                            ] = recv
    +                        refs = []
    +                        _csharp_collect_type_refs(
    +                            ptype, source, False, refs, csharp_type_params
    +                        )
    +                        for ref_name, role, qualified, qualifier in refs:
    +                            ctx = "generic_arg" if role == "generic_arg" else "field"
    +                            target_nid = ensure_named_node(ref_name, p_line)
    +                            if target_nid != class_nid:
    +                                metadata = {"ref_token": ref_name}
    +                                if qualified:
    +                                    metadata["qualified"] = True
    +                                if qualifier:
    +                                    metadata["ref_qualifier"] = qualifier
    +                                add_edge(class_nid, target_nid, "references",
    +                                         p_line, context=ctx, metadata=metadata)
    +
                 # C++-specific: inheritance via base_class_clause (class and struct).

    Results on the repro from the issue

    affected "IDep" before → after:

      - CaseB [references] Cases.cs:L24
      - CaseC [references] Cases.cs:L32
      - Dep   [implements] Cases.cs:L9
      - .Run() [calls]     Cases.cs:L26
    + - CaseA [references] Cases.cs:L16
    + - .Run() [calls]     Cases.cs:L18

    Case A is now discoverable and its calls edge is restored. Case C is untouched, as expected —
    that one is #2624.

    Also verified:

    • positional record parameters (record RecCase(IDep Dep)) now emit references[field]
    • record struct / struct primary constructors use the same parameter_list shape and are covered
    • type parameters are correctly skipped: class G<T>(IDep dep, T item) yields a ref to IDep only,
      no phantom T node

    Test suite

    baseline (0738af3):  23 failed, 4248 passed, 159 skipped
    patched + 4 tests:   24 failed, 4251 passed, 159 skipped
    

    Correction to my earlier wording here: the counts are not identical, and I should not have
    said the failure sets were byte-identical. The one differing entry is
    tests/test_labeling.py::test_label_communities_batches_when_over_batch_size, and it is
    flaky on pristine HEAD — run in isolation on unmodified 0738af3 it failed 4 of 5 times,
    versus 1 of 5 with the patch applied. It is unrelated to C# extraction and this change does not
    touch it. Every other failure is pre-existing and identical across both runs
    (test_terraform.py, test_skillgen.py, test_ollama_retry_cap.py, test_install_references.py).

    The three C# suites (test_csharp_member_calls, test_csharp_type_resolution,
    test_csharp_partial_classes) pass 83/83 with the four new cases added. Each of the four fails
    on unpatched HEAD and passes with the patch.

    On a real codebase

    Re-extracting a 103-file C# project that uses primary-constructor DI: 3,129 → 3,174 edges
    (+30 references, +15 calls). affected on one interface went from 1 node to 16, now
    correctly including the service class that injects it and each of its delegating methods.

    I have not added tests to tests/test_csharp_member_calls.py yet — happy to add the four cases
    above if you'd like this as a PR.

  2. safishamsi commented on Aug 19, 2026

    @safishamsi
    Member

    Fixed in v0.9.47: https://github.com/Graphify-Labs/graphify/releases/tag/v0.9.47 (C# 12 primary-constructor parameters are now walked for references and calls). Closing as resolved.

  3. brobl2008 commented on Aug 20, 2026

    @brobl2008
    ContributorAuthor

    Follow-up from this work: filed #2911 for two remaining C# generic-type-argument gaps found while validating 0.9.48 — type arguments are captured in property/return/parameter position but dropped in field and call-site position.

    The call-site case covers the standard services.AddScoped<IThing, Thing>() DI registration, so the interface→implementation binding is absent from the graph. Distinct from #2624/#2676, which repair the calls edge to the invoked method by stripping the type arguments rather than emitting them as references — the two are complementary.

    Confirming for anyone landing here: the primary-constructor fix from this issue is present and working in both 0.9.47 and 0.9.48.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions