4

AutoMapper Documentationによると、これを使用してカスタム型コンバーターのインスタンスを作成して使用できるはずです。

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;
    }
}

この単純なテストは、日付プロパティの 1 つが正しく変換されることをアサートする必要があります。

[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()ですか?

4

2 に答える 2