title: Projection using contextual values in AutoMapper
body: <p>I'm currently evaluation whether AutoMapper can be of benefit to our project. I'm working on a RESTful Web API using ASP.NET Web API, and one of the things I must return is a resource that contains links. Consider this simplified example, using the following domain object:</p>
  
  <pre><code>public class Customer
  {
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I need to map this into a resource object, sort of like a DTO but with added properties to facilitate REST. This is what my resource object may look like:</p>
  
  <pre><code>public class CustomerResource
  {
      public string Name { get; set; }
      public Dictionary&lt;string, string&gt; Links { get; set; }
  }
  </code></pre>
  
  <p>The Links property will need to contain links to related resources. Right now, I could construct them using the following approach:</p>
  
  <pre><code>public IEnumerable&lt;CustomerResource&gt; Get()
  {
      Func&lt;Customer, CustomerResource&gt; map = customer =&gt; 
          new CustomerResource
          {
              Name = customer.Name,
              Links = new Dictionary&lt;string, string&gt;()
              {
                  {"self", Url.Link("DefaultApi", new { controller = "Customers", name = customer.Name })}
              }
          }
  
      var customers = Repository.GetAll();
      return customers.Select(map);
  }
  </code></pre>
  
  <p>...but this is pretty tedious and I have a lot of nested resources and such. The problem that I see is that I can't use AutoMapper because it doesn't let me provide certain things needed during projection that are scoped to the point where the mapping operation is performed. In this case, the Url property of the ApiController provides the UrlHelper instance that I need to create the links for me, but there may be other cases.</p>
  
  <p>How would you solve this conundrum?</p>
  
  <p>P.S. I typed up this code specifically for this question, and it compiled in your head but may fail in your favorite IDE.</p>