title: AutoMapper - Mapping derived classes without abstract class on source side
body: <p>I am trying to map the following scenario:</p>
  
  <pre><code>// SourceA + SourceB to not derive from a shared base class.
  class SourceCollection
  {
      IList&lt;SourceA&gt; ACollection;
      IList&lt;SourceB&gt; BCollection;
  
      // ... other properties ...
  }
  
  class DestCollection
  {
      IList&lt;DestBase&gt; Collection;
  
      // ... other properties ...
  }
  
  abstract class DestBase { }
  
  // In their destination form, DestA + DestB share DestBase as a base class.
  class DestA : DestBase { }
  class DestB : DestBase { }
  </code></pre>
  
  <p>When I map SourceCollection > DestCollection I want each of the collections to be gathered into a single collection. Ideally I would like to do this without a custom resolver, since AutoMapper understands how to map SourceA > DestA and SourceB > DestB fine. I just need it to realise that SourceA can map to DestBase as DestA, as DestA derives from DestBase.</p>
  
  <p>As there is no SourceBase I can't just map that to DestBase and use .Include.</p>
  
  <p>I'm guessing this might require a custom resolver since it is two collections merging into one (I would just expect the result to be concatonated), but it would be nice if it didn't require it. Or at least I could write a single custom resolver that was generic enough to not require to be changed if SourceC + DestC came along.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>This is a ValueResolver it can be achieved with, however it does require accounting for each type to resolve manually:</p>
  
  <pre><code>public class BaseCollectionResolver : ValueResolver&lt; SourceCollection, IList&lt;DestBase&gt; &gt;
  {
      protected override IList&lt;DestBase&gt; ResolveCore(SourceCollection source)
      {
          var items = new List&lt;DestBase&gt;();
  
          foreach (var sourceA in source.ACollection)
              items.Add( Mapper.Map&lt;SourceA, DestA&gt;(sourceA) );
  
          foreach (var sourceB in source.BCollection)
              items.Add( Mapper.Map&lt;SourceB, DestB&gt;(sourceB) );
  
          return items;
      }
  }
  </code></pre>
  
  <p>And then mapped accordingly:</p>
  
  <pre><code>Mapper.CreateMap&lt;SourceCollection, DestCollection&gt;()
        .ForMember(dest =&gt; dest.Collection, m =&gt; m.ResolveUsing&lt;BaseCollectionResolver&gt;());
  </code></pre>