What is the best approach for using AutoMapper with value objects with static factory methods:
public class ImmutableDetail
{
public static ImmutableDetail Create(string detail) => new ImmutableDetail(detail);
private ImmutableDetail(string detail)
{
Detail = detail;
}
public string Detail { get;}
}
Where I want to be able to:
var immutableDetails = Mapper.Map<ImmutableDetail>(source);
With below classes:
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; }
}
you can make a mapping like this:
Mapper.CreateMap<DummySource, ImmutableDetail>().ConstructUsing((DummySource ds) => ImmutableDetail.Create(ds.Detail));
var source = new DummySource { Detail = "Hello" };
var immutableDetails = Mapper.Map<ImmutableDetail>(source);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With