According to the AutoMapper Documentation, I should be able 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 source and destination types:
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();
// do some conversion
return dest;
}
}
This simple test should assert that one of the date properties get 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())
); // exception is thrown here
Assert.AreEqual(destination.Value2.Year, 2000);
}
}
But I already get an exception before the assert happens:
System.InvalidCastException : Unable to cast object of type 'SourceDestinationTypeConverter ' to type 'Destination'
.
My question now is, how do I use a custom type converter using ConstructServicesUsing()
?