Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper with static factory methods

Tags:

c#

automapper

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);
like image 962
gumaflux Avatar asked Oct 15 '25 13:10

gumaflux


1 Answers

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);
like image 153
Bob Dust Avatar answered Oct 17 '25 02:10

Bob Dust



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!