JasonBock / InlineMapping

Using the Compiler API for object mapping
MIT License
63 stars 11 forks source link

Consider Supporting Custom Constructors #20

Closed JasonBock closed 3 years ago

JasonBock commented 3 years ago

Right now the target type needs a no-argument constructor, so InlineMapping can create an instance of it, and then it maps the properties. This can get in the way of the new record syntax:

[MapTo(Destination)]
public record Source(Guid Id, string Name);
public record Destination(Guid Id, string Name);

Arguably, it would be nice to have MapToDestination() use the constructor and pass the values in from the source properties. But this is a very slippery slope. What if the two types aren't records? Or they are records and don't use this shorthand notation? If the properties are PascalCased, and the parameters camelCased, how would I know for sure what maps to what?

I'll leave this issue for now, but I think I'd need to constrain this in some way. Meaning, I only match for constructors if there isn't a no-argument constructor, and then I do a case-insensitive match.

JasonBock commented 3 years ago

Maybe what needs to be done here is provide overloads to the MapTo() for each accessible constructor on the destination type. For example, with the Destination type defined above, we'd have:

var source = new Source(Guid.NewGuid(), "Joe");
var destination = source.MapToDestination(Guid.NewGuid(), "Jim");

What's done with the constructor arguments is immaterial to InlineMapping.

JasonBock commented 3 years ago

Work todo: