Note that there are some explanatory texts on larger screens.

plurals
  1. POAutoMapper custom type convert using ConstructServicesUsing
    primarykey
    data
    text
    <p>According to the <a href="https://github.com/AutoMapper/AutoMapper/wiki/Containers" rel="nofollow">AutoMapper Documentation</a>, I should be able to create and use an instance of a Custom Type Converter using this:</p> <pre><code>var dest = Mapper.Map&lt;Source, Destination&gt;(new Source { Value = 15 }, opt =&gt; opt.ConstructServicesUsing(childContainer.GetInstance)); </code></pre> <p>I have the following source and destination types:</p> <pre><code>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; } } </code></pre> <p>And the following type converters:</p> <pre><code>public class DateTimeTypeConverter : ITypeConverter&lt;string, DateTime&gt; { public DateTime Convert(ResolutionContext context) { return System.Convert.ToDateTime(context.SourceValue); } } public class SourceDestinationTypeConverter : ITypeConverter&lt;Source, Destination&gt; { public Destination Convert(ResolutionContext context) { var dest = new Destination(); // do some conversion return dest; } } </code></pre> <p>This simple test should assert that one of the date properties get converted correctly:</p> <pre><code>[TestFixture] public class CustomTypeConverterTest { [Test] public void ShouldMap() { Mapper.CreateMap&lt;string, DateTime&gt;().ConvertUsing(new DateTimeTypeConverter()); Mapper.CreateMap&lt;Source, Destination&gt;().ConstructUsingServiceLocator(); var destination = Mapper.Map&lt;Source, Destination&gt;( new Source { Value1 = "15", Value2 = "01/01/2000", }, options =&gt; options.ConstructServicesUsing( type =&gt; new SourceDestinationTypeConverter()) ); // exception is thrown here Assert.AreEqual(destination.Value2.Year, 2000); } } </code></pre> <p>But I already get an exception before the assert happens:</p> <p><code>System.InvalidCastException : Unable to cast object of type 'SourceDestinationTypeConverter ' to type 'Destination'</code>.</p> <p>My question now is, how do I use a custom type converter using <code>ConstructServicesUsing()</code>?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload