gumaflux gumaflux - 7 days ago 5
C# Question

AutoMapper with static factory methods

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);

Answer

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);