Search code examples
c#asp.netwebformsautomapperautomapper-5

Auto Mapper 5, no Ioc and Webforms


Now that AutoMapper is abolishing both the static API and the ability to change the mappings at runtime I have a problem with my WebForms application without an IoC manager.

For the sake of this question take as given I cannot introduce an IoC manager into this application, and while it would be "good to do" the application has been working fine without it for a number of years, and it cannot be done right at the moment. In the future maybe, but not now.

With AutoMapper what I used to do before was have a method in each class I instantiated that was called automatically by the constructor. In that method I would have the necessary:

Mapper.CreateMap<>()

calls. This has the following advantages:

  • I only mapped what I needed per request (and depending on program flow this list of mappings would grow to what I needed)
  • All types were "local" - meaning I did not have to reference other projects in the solution

I was happy to live with the performance hit each request of doing things this way instead of doing this once in Application_Start().

However with AutoMapper 5... Having read migrating from the static API it appears that I now have to:

  1. Do all the mappings "somewhere" where I have access to all the types I want to map. So no matter where I put this I have to reference every other assembly in my solution?
  2. Having stored the MapperConfiguration() instance somewhere globally accessible - lets say either HttpContext or HttpApplication so I can call MapperConfiguration.CreateMapper() I now need to make sure that I have access to HttpContext / HttpApplication everywhere. This ultimately means projects that have no need of say the HttpContext will now need to access it.

If my assumptions in 1. & 2. above are correct I now have a big mess of tightly coupled spaghetti code.

So my question is this:

How do I use AutoMapper 5 in a webforms application with numerous projects (and hence many types) in the solution, without an IoC elegantly?


Solution

  • AutoMapper isn't abolishing the static API. Just the pieces that modify configuration at will. It turns out that allowing Mapper.CreateMap at any time forces me to make mapping sloooooooow.

    That wiki page I forgot to delete. Here's the actual guidance:

    https://github.com/AutoMapper/AutoMapper/wiki/Static-and-Instance-API

    And 5.0 upgrade guide:

    https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide

    The overall story is "get rid of your Mapper.CreateMap calls sprinkled everywhere and put them in initialization". You can use profiles to help you out.

    But Mapper.CreateMap sprinkled throughout your app was ALWAYS dangerous. It meant you couldn't use Mapper.AssertConfigurationIsValid, which is very dangerous to skip. If you can't assert configuration validation, you shouldn't use AutoMapper.