title: Asp Net Core DI for AutoMapper
body: <p>I have a question regarding dependency injection for AutoMapper in ASP NET Core. I know that there is automapper extension for DI available when implementing custom <code>IValueResolver</code> and <code>IMemberValueResolver</code>. This works only if the custom value resolvers are created by AutoMapper/DI. This unfortunately does not work if I need to created the value resolver manually. Also please note that I DON'T WANT to pass items when I call <code>mapper.Map&lt;&gt;()</code> method, because I don't want the consumer of <code>IMapper</code> to have any awareness of any extra parameters at runtime</p>
  
  <p>Consider the code below:</p>
  
  <pre><code>class Entity1
  {
      public int MyProperty1 { get; set; } 
  }
  
  class Dto1 
  {
      public int MyProperty1 { get; set; } 
      public string CustomProperty { get; set; } 
  }
  </code></pre>
  
  <p>In MyProfile.cs</p>
  
  <pre><code>CreateMap&lt;Entity1, Dto1&gt;()
      .ForMember(x =&gt; x.CustomProperty, 
         opt =&gt; opt.ResolveUsing(new MyCustomPropertyResolver("Important value")));
  </code></pre>
  
  <p>And MyCustomPropertyResolver is like this:</p>
  
  <pre><code>public class MyCustomPropertyResolver : IValueResolver&lt;Entity1, Dto1, string&gt;
  {
      string _someValue;
      public MyCustomPropertyResolver(string someValue)
      {
          _someValue = someValue;
      }
      string Resolve(Entity1 source, Dto1 destination, string destMember, ResolutionContext context)
      {
          //I need IHttpContextAccessor ..... How can I do that???
      } 
  }
  </code></pre>
  
  <p>Of course, If I did this:</p>
  
  <pre><code>CreateMap&lt;Entity1, Dto1&gt;()
      .ForMember(x =&gt; x.CustomProperty, 
         opt =&gt; opt.ResolveUsing&lt;MyCustomPropertyResolver&gt;()));
  </code></pre>
  
  <p>I can use DI and add <code>IHttpContextAccessor</code> to <code>MyCustomPropertyResolver</code> constructor, but then I won't be able to pass any extra params to the resolver that are also important to resolve the actual value. Is there a way to achieve this? The only way I was able to achieve this is by adding a static property on <code>MyProfile</code> class and set it via <code>ActionFilter</code> on the controller serving the request. Although this work but I don't like this solution because it creates unwanted dependencies. The official solution on AutoMapper is to do this: </p>
  
  <pre><code>// This solution is not good enough for my need
  var dto = mapper.Map&lt;Dto1&gt;(entity, opt =&gt; { opt.Items["AnyThing"] = Whatever; }); 
  </code></pre>
  
  <p>With the above code I can pass <code>HttpContext</code> to the items dictionary, but this will make the mapper consumer required to pass in parameters that might not be aware of. </p>
  
  <p>My code in reality is much more complex but it is conceptually using the same example above.</p>