Click here to Skip to main content
15,884,537 members
Articles / Programming Languages / C#

Validate Your AutoMapper Mappings

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
25 Mar 2018MIT3 min read 25.7K   222   11  
Automatically validate your AutoMapper mapping after each and every build with AutoMapperPostBuild

Introduction

If you write mapping or translation code for setting properties from one object to another, you have probably used [AutoMapper](http://automapper.org) by [Jimmy Bogard](https://github.com/jbogard). AutoMapper is a simple little library built to solve a deceptively complex problem. One downside is, often you will find out during runtime that you missed one or more properties in a mapping. This project will let you have feedback directly after compile whether or not your mapping is correct. You don't want to wait for the runtime exceptions (well, actually you will, but......just read on).

Basics

AutoMapper is not a silver bullet. You can find a lot of good posts or rants about why one should not use AutoMapper. Even Jimmy Bogard himself describes scenarios in which you might better not use AutoMapper. Nevertheless, in the projects that I encounter that rely heavily on AutoMapper, I implement the AutoMapperPostBuilder. The build in functionality of AutoMapper `Mapper.AssertConfigurationIsValid()` is used directly after compilation. Just by calling an Invoke in the postbuild event of your project in which you are using AutoMapper, it will give you insight into what properties you missed in your mapping.

Getting Started

Reference the AutoMapperPostBuilder project and reference it with the option 'Copy Local = True'. This will ensure that the AutoMapperPostBuilder.exe is copied to your project output folder. In the properties of your project, fill in the 'Post-build event command line':

JavaScript
"$(TargetDir)AutoMapperPostBuilder.exe" $(TargetPath)AutoMapperPostBuilder_Sample.MappingClass Invoke

Fill in the Post-build event command line

Where in this example the class to be invoked is the AutoMapperPostBuilder_Sample.MappingClass. Just replace that name with the class name you want to invoke.

The AutoMapperPostBuilder.exe takes the following arguments:

  • full path of your project output (eg. bin/debug/YourAssembly.dll)
  • the namespace and class name of your mapping class
  • the `Invoke` command

The class you want to invoke needs to have the following method:

C#
public static void Invoke() {}

In the (static) constructor, where you probably have your standard mapping all written out, you need to end with:

C#
Mapper.AssertConfigurationIsValid();

A simple mapping class could look just like this:

C#
using AutoMapper;
namespace AutoMapperPostBuilder_Sample
{
    static class MappingClass
    {
        static MappingClass()
        {            
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<sampleclassb_1, sampleclassa_1="">()        
                    .ForMember(dest => dest.InnerProp1, opt => opt.MapFrom(src => src.InnerProp10))
                    .ForMember(dest => dest.InnerProp2, opt => opt.MapFrom(src => src.InnerProp20));
            });
            Mapper.AssertConfigurationIsValid();
        }
        public static void Invoke() {}        
    }
}

The Result

Now, if you compile your project and the build succeeds (initially), the post-build event will fire the AutoMapperPostBuilder.exe that will look for the specified class and invokes it. This will build your mapping and will call AssertConfigurationIsValid. If any of your mappings is faulty, it will display it in your build-output-window.

Build-output-window showing what is wrong with your mapping right after you build your project

Even better, the post-build event will notice that AutoMapperPostBuilder.exe has exited with code 1. This will result in a fail build. And that's exactly what you want, because you do not want to wait for the exception by starting your application and just finally hit that code.

Build-output-window showing that the AutoMapperPostBuilder found all the mappings to be okay

How Does This Work

The AutoMapperPostBuilder invokes the static method Invoke(). Which in turn causes the static constructor to be called. Because the mappings are written in or called from the constructor, we are able to make use of the Mapper.AssertConfigurationIsValid(). AutoMapper by itself will throw exceptions with detailed information regarding the mappings that are invalid. These exceptions are caught by AutoMapperPostBuilder.exe and written to the console. These console outputs are displayed in your Build-output in Visual Studio or probably any IDE you are working in.

Sample Project

The project AutoMapperPostBuilder_Sample, which is included in the AutoMapperPostBuilder solution shows just how easy it is to implement. The current code compiles just fine, and therefore you will not see much in your Build-output window. Just comment out the mapping of a certain property, and you'll see the hint that AutoMapper will give you.

Github

Find it on GitHub at https://github.com/cvanbergen/AutoMapperPostBuilder.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior) NoNerds
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --