将AutoMapper与具有静态工厂方法的值对象一起使用的最佳方法是什么:
public class ImmutableDetail
{
public static ImmutableDetail Create(string detail) => new ImmutableDetail(detail);
private ImmutableDetail(string detail)
{
Detail = detail;
}
public string Detail { get;}
}
我希望能够:
var immutableDetails = Mapper.Map<ImmutableDetail>(source);
答案 0 :(得分:3)
以下课程:
public class DummySource
{
public string Detail { get; set; }
}
public class ImmutableDetail
{
public static ImmutableDetail Create(string detail) { return new ImmutableDetail(detail); }
private ImmutableDetail(string detail)
{
Detail = detail;
}
public string Detail { get; private set; }
}
你可以制作这样的映射:
Mapper.CreateMap<DummySource, ImmutableDetail>().ConstructUsing((DummySource ds) => ImmutableDetail.Create(ds.Detail));
var source = new DummySource { Detail = "Hello" };
var immutableDetails = Mapper.Map<ImmutableDetail>(source);