我正在尝试选择界面将转换为什么。我把地图设置成这样:
CreateMap<ICustomerServiceDto, dynamic>()
.ConvertUsing(service => CreateForServices(service));
CreateMap<ICustomerServiceDto, CustomerServiceTelecomDto>();
CreateMap<CustomerServiceTelecomDto, CustomerServiceTelecomModel>();
和CreateForServices
private ICustomerServiceModel CreateForServices(ICustomerServiceDto type)
{
if (type is CustomerServiceTelecomDto telecom)
{
//I do not like this solution
return new CustomerServiceTelecomModel(telecom.Value);
}
throw new InvalidOperationException($"Unknown type: {type.GetType().FullName}");
}
我将添加其他类型稍后转换,但上面的工作。
但是我不希望在CustomerServiceTelecomModel中填充构造函数,AutoMapper已经知道如何将CustomerServiceTelecomDto映射到CustomerServiceTelecomModel,所以我可以以某种方式使用该映射吗?
这是在Mapper配置文件中,因此据我所知,我无法访问Mapper实例并手动执行映射。
您可以使用ConvertUsing
的另一个重载,它提供解析上下文和对映射器的引用。
CreateMap<ICustomerServiceDto, dynamic>()
.ConvertUsing((service, _, ctx) => CreateForServices(ctx, service));
private ICustomerServiceModel CreateForServices(ResolutionContext ctx, ICustomerServiceDto type)
{
if (type is CustomerServiceTelecomDto telecom)
{
return ctx.Mapper.Map<CustomerServiceTelecomModel>(type);
}
throw new InvalidOperationException($"Unknown type: {type.GetType().FullName}");
}