MapsterMapper / Mapster

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

AfterMapping causing null reference exception with interface mapping #547

Closed tariano closed 1 year ago

tariano commented 1 year ago

When using interface mapping with AfterMapping, like so:

[Mapper]
public interface ITheMapper {
    To Map(From from);
}

public class MapReg : IRegister {
    public void Register(TypeAdapterConfig config) {
        config.NewConfig<From, To>()
            .AfterMapping(to => { Console.WriteLine("Mapped!"); });
    }
}

Then in the generated code, the Action is null, so Action1.Invoke(result) results in null reference exception:

public partial class TheMapper : ITheMapper
{
    private Action<To> Action1;

    public To Map(From p1)
    {
        if (p1 == null)
        {
            return null;
        }
        To result = new To();
        Action1.Invoke(result);
        return result;

    }
}

That's the main:

using Microsoft.Extensions.DependencyInjection;
using Question;

var services = new ServiceCollection();
services.AddSingleton<ITheMapper,TheMapper>();
var myMapper = services.BuildServiceProvider().GetService<ITheMapper>();
myMapper!.Map(new From() {Name = "self"});
andrerav commented 1 year ago

@tariano I believe block expressions are not supported for code generation. Can you try moving your code to an external method and call that method as a inline expression instead?

Edit: Please see here: https://github.com/MapsterMapper/Mapster/wiki/Before-after-mapping