title: AutoMapper AfterMap
body: <p>I have some code that pretty much looks like below, see working example at <a href="https://dotnetfiddle.net/wuE81t" rel="nofollow">https://dotnetfiddle.net/wuE81t</a>. </p>
  
  <pre><code>public class Program
  {
      public static void Main()
      {
          Mapper.CreateMap&lt;Foo, Bar&gt;()
              .AfterMap((s, d) =&gt; {
                  var stuff = SomeController.GetStuff(DateTime.Now.Second);
                  d.Stuff = stuff.Contains(s.Name);
              });
  
          var foo = new List&lt;Foo&gt;() {
              new Foo() { Name = "joe", Age = 10 },
              new Foo() { Name = "jane", Age = 20 },
          };
  
          var bar = Mapper.Map&lt;List&lt;Foo&gt;, List&lt;Bar&gt;&gt;(foo);
      }
  }
  
  public class Foo
  {
        public string Name { get; set; }
        public int Age { get; set; }
  }
  
  public class Bar
  {
        public string Name { get; set; }
        public int Age { get; set; }
        public bool Stuff { get; set; }
  }
  
  public static class SomeController
  {
      public static List&lt;string&gt; GetStuff(int currentUserId)
      {
          return new List&lt;string&gt;() { "jane" };
      }
  }
  </code></pre>
  
  <p>The problem I have is that GetStuff is called for each of the items in the source list, and it's a quite heavy operation, so I'd like to optimize it by only calling it once. In my actual code, GetStuff uses the currentUserId parameter.</p>
  
  <p>I have currently solved it by moving GetStuff to after Mapper.Map, but since we have quite a few places where this is called, it's much uglier than using AfterMap. There is also a much greater risk that a future developer will forget the required extra call.</p>
  
  <pre><code>public static void Main()
  {
      Mapper.CreateMap&lt;Foo, Bar&gt;();
  
      var foo = new List&lt;Foo&gt;() {
          new Foo() { Name = "joe", Age = 10 },
          new Foo() { Name = "jane", Age = 20 },
      };
  
      var bar = Mapper.Map&lt;List&lt;Foo&gt;, List&lt;Bar&gt;&gt;(foo);
      AddStuff(bar); // Required extra call!
  
      bar.Dump();
  }
  
  private static void AddStuff(List&lt;Bar&gt; bar)
  {
      var stuff = SomeController.GetStuff(DateTime.Now.Second);
      foreach(var b in bar)
          b.Stuff = stuff.Contains(b.Name);       
  }
  </code></pre>
  
  <p>Is there a better solution?</p>