Skip to content

Generated factories fail to compile for init-only or required properties #2

Description

@kgkoutis

Problem

GetPropertiesToSet in DataFactoryWriter.cs treats every settable property the same way and emits a post-construction assignment:

var o = new T(...);
var o0 = provider.Resolve<...>(...);
if (o0.IsResolved)
{
    o.SomeProperty = o0.Value;
}

This doesn't compile when SomeProperty is:

  • init-only ({ get; init; }) — CS8852, init-only properties can only be assigned in an object initializer.
  • required — CS9035, required members must be assigned in the object initializer of the enclosing new expression (or via a constructor annotated [SetsRequiredMembers]).

Since GetPropertiesToSet only filters on GetMethod/SetMethod being non-null, it doesn't distinguish these from ordinary mutable properties, so any [DataFactory]-registered type using init or required members currently fails to compile.

Repro

[DataFactory(typeof(MyType))]
public partial class MyTests
{
    private sealed class MyType
    {
        public required int SomeInt { get; set; }
        public string? SomeString { get; init; }
    }
}

Generated code emits o.SomeInt = ...; and o.SomeString = ...; as separate statements after new MyType(), which fails to compile.

Fix

I have a fix and will open a PR shortly: split properties into an init-only/required bucket and a regular mutable bucket. The former get resolved into temp variables before construction and assigned inside the object-initializer block of the new expression; the latter keep the existing conditional post-construction assignment. Verified against init-only classes, required classes, records with additional init properties, structs with required members, nested required reference-typed properties, and a self-referencing required property forced through the recursion guard.

Activity

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions