MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.3k stars 328 forks source link

Add IMapFrom interface for automatic mapping configuration #533

Closed stormaref closed 1 year ago

stormaref commented 1 year ago

Creating IMapFrom interface now destination type can inherit from an interface named IMapFrom and they can configure mapping in the same class like this:

public class InheritedDestinationModel : IMapFrom<SourceModel>
{
    public string Type { get; set; }
    public int Value { get; set; }

    public void ConfigureMapping(TypeAdapterConfig config)
    {
        config.NewConfig<SourceModel, InheritedDestinationModel>()
            .Map(dest => dest.Value, _ => DesireValues.Number);
    }
}

and even if you don't implement the method it will automatically create a new config for desire types ex:

public class DestinationModel : IMapFrom<SourceModel>
{
    public string Type { get; set; }
}

I've added a new extension method to TypeAdapterConfig named ScanInheritedTypes like this:

TypeAdapterConfig.GlobalSettings.ScanInheritedTypes(Assembly.GetExecutingAssembly());

I've created tests for all situations and tests are passed as soon as this pull request merged I will update wiki page

andrerav commented 1 year ago

Thanks @stormaref!