According to AutoMapper Documentation , I would have to create and use an instance of a custom type converter using this:
var dest = Mapper.Map<Source, Destination>(new Source { Value = 15 }, opt => opt.ConstructServicesUsing(childContainer.GetInstance));
I have the following types of sources and destinations:
public class Source { public string Value1 { get; set; } public string Value2 { get; set; } public string Value3 { get; set; } } public class Destination { public int Value1 { get; set; } public DateTime Value2 { get; set; } public Type Value3 { get; set; } }
And the following type converters:
public class DateTimeTypeConverter : ITypeConverter<string, DateTime> { public DateTime Convert(ResolutionContext context) { return System.Convert.ToDateTime(context.SourceValue); } } public class SourceDestinationTypeConverter : ITypeConverter<Source, Destination> { public Destination Convert(ResolutionContext context) { var dest = new Destination();
This simple test should state that one of the date properties is converted correctly:
[TestFixture] public class CustomTypeConverterTest { [Test] public void ShouldMap() { Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter()); Mapper.CreateMap<Source, Destination>().ConstructUsingServiceLocator(); var destination = Mapper.Map<Source, Destination>( new Source { Value1 = "15", Value2 = "01/01/2000", }, options => options.ConstructServicesUsing( type => new SourceDestinationTypeConverter()) );
But I am already getting an exception before the statement happens:
System.InvalidCastException : Unable to cast object of type 'SourceDestinationTypeConverter ' to type 'Destination' .
Now my question is: how to use a custom type converter using ConstructServicesUsing() ?