title: AutoMapper Profiles and Unit Testing
body: <p>I'm rolling over my AutoMappers from using one large AutoMapperConfiguration class to using actual profiles. Global now looks like so (forgive the Open/Close violation for now)</p>
  
  <pre><code>Mapper.Initialize(x =&gt;
                         {
                            x.AddProfile&lt;ABCMappingProfile&gt;();
                            x.AddProfile&lt;XYZMappingProfile&gt;();
                            // etc., etc.
                    });
  </code></pre>
  
  <p>The key piece that got me over the top and the hurdle that had previously always stopped me from using profiles was my ninject binding. I could never get the binding to work.
  Prior I had this binding:</p>
  
  <pre><code>Bind&lt;IMappingEngine&gt;().ToConstant(Mapper.Engine).InSingletonScope();
  </code></pre>
  
  <p>I've since migrated to this binding:</p>
  
  <pre><code>Bind&lt;IMappingEngine&gt;().ToMethod(context =&gt; Mapper.Engine);
  </code></pre>
  
  <p>This now works, the app is functional, I have profiles, and things are good.</p>
  
  <p>The hitch is now in my unit tests. Using NUnit, I'd setup my constructor dependencies.</p>
  
  <pre><code>private readonly IMappingEngine _mappingEngine = Mapper.Engine;
  </code></pre>
  
  <p>and then in my [Setup] method I'd construct my MVC controller and call the AutoMapperConfiguration class.</p>
  
  <pre><code>[SetUp]
  public void Setup()
  {
      _apiController = new ApiController(_mappingEngine);
      AutoMapperConfiguration.Configure();
  }
  </code></pre>
  
  <p>which I've now modified to.</p>
  
  <pre><code>[SetUp]
  public void Setup()
  {
      _apiController = new ApiController(_mappingEngine);
  
      Mapper.Initialize(x =&gt;
                            {
                                x.AddProfile&lt;ABCMappingProfile&gt;();
                                x.AddProfile&lt;XYZMappingProfile&gt;();
                                // etc., etc.
                            });
  }
  </code></pre>
  
  <p>Unfortunately, this does not seem to work. The mappings do not appear to be getting picked up as when I hit a method that uses mappings, AutoMapper throws an exception stating the mapping doesn't exist. Any suggestions on how/what to change the the mapper definition/injection in the test to resolve this? I'm guessing the definition of the IMappingEngine field is my problem but unsure of what options I have.</p>
  
  <p>Thanks</p>