根据AutoMapper 文档,我应该能够使用以下方法创建和使用自定义类型转换器的实例:
var dest = Mapper.Map<Source, Destination>(new Source { Value = 15 },
opt => opt.ConstructServicesUsing(childContainer.GetInstance));
我有以下源和目标类型:
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; }
}
以及以下类型转换器:
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;
}
}
这个简单的测试应该断言日期属性之一得到正确转换:
[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);
}
}
但是在断言发生之前我已经得到了一个异常:
System.InvalidCastException : Unable to cast object of type 'SourceDestinationTypeConverter ' to type 'Destination'
.
我现在的问题是,如何使用自定义类型转换器ConstructServicesUsing()
?