Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Validate Your AutoMapper Mappings

0.00/5 (No votes)
25 Mar 2018 1  
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':

"$(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:

public static void Invoke() {}

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

Mapper.AssertConfigurationIsValid();

A simple mapping class could look just like this:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here