Skip to content

Conversation

@Tim-Maes
Copy link
Owner

fixes #253

When using [Facet] with GenerateParameterlessConstructor = false, users who have custom initialization logic in their parameterless constructor had no way to ensure that logic runs when using ToFacet<>() or constructing from a source.

public class ModelType
{
    public int MaxValue { get; set; }
}

[Facet(typeof(ModelType), GenerateParameterlessConstructor = false)]
public partial class MyType
{
    public int Value { get; set; }

    public MyType()
    {
        // This initialization logic was NOT being called when mapping
        Value = 100;
    }
}

Feature

Added a new ChainToParameterlessConstructor property to the [Facet] attribute. When set to true, the generated constructor that takes the source type will chain to the parameterless constructor using : this().

Usage

public class ModelType
{
    public int MaxValue { get; set; }
}

[Facet(typeof(ModelType), GenerateParameterlessConstructor = false, ChainToParameterlessConstructor = true)]
public partial class MyType
{
    public int Value { get; set; }
    public bool Initialized { get; set; }

    public MyType()
    {
        // This initialization logic WILL now run when mapping
        Value = 100;
        Initialized = true;
    }
}

// Usage
var source = new ModelType { MaxValue = 42 };
var dto = new MyType(source);

// dto.Value == 100 (from parameterless constructor)
// dto.Initialized == true (from parameterless constructor)
// dto.MaxValue == 42 (from source mapping)

Generated Code

With ChainToParameterlessConstructor = true:

public partial class MyType
{
    public int MaxValue { get; set; }

    public MyType(ModelType source) : this()  // <-- Chains to parameterless ctor
    {
        this.MaxValue = source.MaxValue;
    }
}

Without chaining (default behavior):

public partial class MyType
{
    public int MaxValue { get; set; }

    public MyType(ModelType source)  // <-- No chaining
    {
        this.MaxValue = source.MaxValue;
    }
}

Notes

  • This feature works with both the main constructor and the depth-aware constructor
  • Default value is false to maintain backward compatibility
  • Can be combined with other attributes like Configuration, BeforeMapConfiguration, etc.

@Tim-Maes Tim-Maes merged commit 7c22c37 into master Jan 27, 2026
2 checks passed
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.

Add option to include in generated parametr constructor the parameterless one existing in class

2 participants