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'.
我仍然面临着关于您想要实现的目标的问题。我已经浏览了几个代码示例(都对您的代码进行了一些修改),并且我设法获得了很多成功的结果。如果我说您正在尝试使用 IoC 容器/对象工厂来创建目标对象的实例以进行转换,我是否正确。 (因为这是 ConstructServicesUsing 的用武之地)。在这里,您传入的是 Converter 对象,它看起来不正确。我在使用 IoC 容器/工厂和自定义转换器时也遇到了问题。
public class StringTypeConverter : ITypeConverter<string, Type>
{
public Type Convert(ResolutionContext context)
{
return Type.GetType(context.SourceValue.ToString());
}
}
public class StringIntConverter : ITypeConverter<string, int>
{
public int Convert(ResolutionContext context)
{
return Int32.Parse(context.SourceValue.ToString());
}
}
Automapper 缺少 String 到 Type 和 String 到 Int 的映射。
我还必须删除以下行