MapsterMapper / Mapster

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

Error: stack overflow when RequireExplicitMapping = true #571

Open pmatrosov opened 1 year ago

pmatrosov commented 1 year ago

Hi! This code generates StackOverlowException while calling method Compile() on versions 7.2.0 , 7.3.0 and 7.4-pre:

using Mapster;

var config = new TypeAdapterConfig
{
    RequireExplicitMapping = true, // comment this to remove StackOverlowException
    RequireDestinationMemberSource = true
};
config.NewConfig<Source, Destination>()/*.MaxDepth(10)*/;
config.Compile(); // StackOverlowException here

public class Source
{
    public string? Identifier { get; set; }
    public Source[]? Inner { get; set; }
}

public class Destination
{
    public string? Identifier { get; set; }
    public Destination[]? Inner { get; set; }
}

I found two workarounds to avoid this problem:

But both solutions are not suitable for me. Is this behavior a bug and how else can it be avoided?

andrerav commented 1 year ago

Can you explain what you expect to happen here?

pmatrosov commented 1 year ago

I expect no exception when using RequireExplicitMapping=true (I don't understand why it has an effect?) and unlimited nesting depth of Source class instance. All Source objects are unique in my case.

thomas-hockings-cs commented 1 year ago

I've also just come across this issue. When RequireExplicitMapping is true a stack overflow exception occurs with a circular reference during compile. The only solution is to use MaxDepth in your mapper because PreserveReference(true) has no effect.

It took me a while to figure this out because it doesn't appear to be documented that circular references are an issue when RequireExplicitMapping = true and it didn't seem like I was in a situation that would require MaxDepth.

I would much prefer to not have to use MaxDepth when RequireExplicitMapping = true.