riok / mapperly

A .NET source generator for generating object mappings. No runtime reflection.
https://mapperly.riok.app
Apache License 2.0
2.94k stars 147 forks source link

Support mapping from a DTO to an object's factory create method #1502

Open skuirrels opened 2 months ago

skuirrels commented 2 months ago

Domain Driven Design is becoming more and more popular and it's common to use a Create Factory method to create objects that have more validation requirements than can be added within just a contractor.

The proposal is to configure the mapping method to specify the factory method needed for object creation, such as in the below:

[Mapper]
public partial class CountryMapper
{
    [MapToFactoryMethod(typeof(Country), nameof(Country.Create))]
    public partial Country MapDtoToCountry(CountryDto dto);
}

Presently this must be performed as below, specifying all fields, which negates the use of a mapper.

[Mapper]
public partial class CountryMapper
{
    public partial Country MapDtoToCountry(CountryDto dto)
    {
        return Country.Create(dto.Code, dto.Name, dto.Continent);
    }
}

Mapster has this feature (albeit using reflection and not source generation) but Mapster is no longer maintained. I feel this is the missing feature to make Mapperly the new defacto standard for dotnet.

latonz commented 1 month ago

This could be implemented but I think a simple property on the ObjectFactoryAttribute should do the job (bool MapToParameters). Feel free to contribute 😉