Search code examples
c#automapperobjectmapperobject-object-mapping

Prevent refactoring mistakes with mapping libraries


Given

class A { string Name {get;set;} }
class B { string Name {get;set;} }

I then use automapper to translate between A and B. Later, I rename A.Name to A.MyName:

class A { string MyName {get;set;} }
class B { string Name {get;set;} }

This will break my mapping, because of implicit configuration. Implicit configuration implicitly create a relationship between A and B. Refactoring algorithm do not recognize this relationship thus producing a break.

What mappers solve this problem?


Solution

  • In AutoMapper, assuming that you have handled all properties in your mappings (by either mapping them or explicitly ignoring them), Mapper.AssertConfigurationIsValid(); is the way to manage this problem.

    As the documentation says:

    Executing this code produces an AutoMapperConfigurationException, with a descriptive message. AutoMapper checks to make sure that every single Destination type member has a corresponding type member on the source type.

    Thus after you have refactored your classes, there will not be a mapping defined, and the test will fail.

    You can put it in a unit test, or in your startup code if you don't have any tests.