MapsterMapper / Mapster

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

Explicit mapping throws on mapping interface into model #433

Open tiger31 opened 2 years ago

tiger31 commented 2 years ago

Code example (net6.0) Mapster version: 7.3.0

Program.cs

using ConsoleApp1;
using Mapster;
using MapsterMapper;

var config = TypeAdapterConfig.GlobalSettings.Clone();
config.RequireExplicitMapping = true;

config.ForType<IFooType, FooModel>()
    .Map(d => d.Foo, s => s.Foo);

var mapper = new Mapper(config);

var fooModel = mapper.Map<FooModel>(FooResolver.Resolve("bar"));

class FooModel
{
    public string Foo { get; set; }
}

FooResolver.cs

namespace ConsoleApp1
{
    public sealed class FooResolver
    {
        public static IFooType Resolve(string foo)
        {
            return new FooType
            {
                Foo = foo
            };
        }

        private class FooType : IFooType
        {
            public string Foo { get; set; }
        }
    }

    public interface IFooType
    {
        public string Foo { get; set; }
    }
}

I expect that on line 13 of Program.cs IFooType returned by FooResolver will be successfully mapped to FooModel but instead I'm getting exception

Unhandled exception. Mapster.CompileException: Error while compiling
source=ConsoleApp1.FooResolver+FooType
destination=FooModel
type=Map
 ---> System.InvalidOperationException: Implicit mapping is not allowed (check GlobalSettings.RequireExplicitMapping) and no configuration exists
   at Mapster.Adapters.BaseAdapter.CreateExpressionBody(Expression source, Expression destination, CompileArgument arg)
   at Mapster.Adapters.BaseAdapter.CreateAdaptFunc(CompileArgument arg)
   at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
   --- End of inner exception stack trace ---
   at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
   at Mapster.TypeAdapterConfig.CreateMapExpression(TypeTuple tuple, MapType mapType)
   at Mapster.TypeAdapterConfig.CreateDynamicMapExpression(TypeTuple tuple)
   at Mapster.TypeAdapterConfig.<GetDynamicMapFunction>b__66_0[TDestination](TypeTuple tuple)
   at Mapster.TypeAdapterConfig.<>c__DisplayClass55_0`1.<AddToHash>b__0(TypeTuple types)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Mapster.TypeAdapterConfig.AddToHash[T](ConcurrentDictionary`2 hash, TypeTuple key, Func`2 func)
   at Mapster.TypeAdapterConfig.GetDynamicMapFunction[TDestination](Type sourceType)
   at MapsterMapper.Mapper.Map[TDestination](Object source)
   at Program.<Main>$(String[] args) in D:\ConsoleApp1\ConsoleApp1\Program.cs:line 13

Do I misunderstand RequireExplicitMappin or is it a bug?