MelGrubb / BuilderGenerator

A source-generator-based implementation of the Builder pattern
https://melgrubb.github.io/BuilderGenerator/
MIT License
36 stars 8 forks source link

internal set properties #15

Closed sonnemaf closed 2 years ago

sonnemaf commented 2 years ago

Hi

The source generator doesn't generate a With/Without method in the builder if the setter of the property is internal.

image

namespace BuilderGeneratorDemo;

class Program {
    static void Main(string[] args) {
        var user = new UserBuilder().WithFirstName("Fons")
                                    .WithLastName("Sonnemans")
                                    .Build();

        Console.WriteLine(user.FirstName);
        Console.WriteLine(user.LastName);
    }
}

[BuilderGenerator.BuilderFor(typeof(User))]
public partial class UserBuilder {
}

public class User {
    public string FirstName { get; internal set; }

    public string LastName { get; set; }

    public DateTime? Date { get; set; }
}
MelGrubb commented 2 years ago

It would be possible for the generator to generate the methods, but unfortunately it can't predict whether or not they will be valid. Your main project is probably exposing internals to the test project via an InternalsVisibleTo attribute on the assembly, right? Well, the generator doesn't really have a way of knowing that. I suppose a parameter on the BuilderFor attribute to include or exclude internals would do the trick, but you'd have to enable it by hand on each class individually.

Maybe there's some way to figure out if the assembly the tests live in is allowed to see the internals of the referenced class through reflection. That would make it automatic. This will take a bit of research, I'm afraid. It seems like it would be possible. I've never had a reason to look into that before.

MelGrubb commented 2 years ago

I think an "Include internals" parameter is probably the safest route at first and something more intelligent could be added later.

sonnemaf commented 2 years ago

I agree, the parameter would work perfectly

MelGrubb commented 2 years ago

v2.1.0 exposes internal properties if explicitly told to in the BuilderFor attribute. Add a second Boolean parameter of "true" to include internals.