未触发AfterMap
时遇到问题。
以下是发生此问题的条件:
ConstructUsing
,因为这里是选择具体类型的地方这里是整个xunit测试(在执行dotnet new xunit -o PbAutoMapper
之后):
using System;
using AutoMapper;
using Xunit;
namespace PbAutoMapper
{
public class UnitTest1
{
[Fact]
public void Test1()
{
var mapperConfig = new MapperConfiguration(config =>
{
config.CreateMap<SourceClass, BaseDestinationClass>()
.ConstructUsing(this.Construct)
.ForMember(i => i.MyNewProperty, o => o.Ignore())
.AfterMap(this.AfterMap);
config.CreateMap<SourceClass, DestinationClass>();
});
var mapper = mapperConfig.CreateMapper();
var src = new SourceClass { MyProperty = 1 };
var dest = mapper.Map<BaseDestinationClass>(src);
Assert.Equal("1", dest.MyNewProperty); // This works...
dest = new DestinationClass();
mapper.Map(src, dest);
Assert.Equal("1", dest.MyNewProperty); // This failed because AfterMap wasn't triggered
}
private DestinationClass Construct(SourceClass s, ResolutionContext ctx)
{
var d = new DestinationClass();
ctx.Mapper.Map(s, d, ctx);
return d;
}
private void AfterMap(SourceClass s, BaseDestinationClass d)
{
d.MyNewProperty = s.MyProperty.ToString();
}
}
public class SourceClass
{
public int MyProperty { get; set; }
}
public abstract class BaseDestinationClass
{
public string MyNewProperty { get; set; }
}
public class DestinationClass : BaseDestinationClass
{
}
}
注意:看起来似乎可以实现不同的这段代码实际上已经过简化,无法以最简单的方式揭示我的问题。