Automapper and XUnit Missing Type Map

So one day I am minding my own business and decide to run unit test and I am hit with this error message.

{"Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nSource -> Destination\r\n"}

This is a pretty self-explanatory message. Looks like we didn't call the method to configure Automapper. In the constructor of the test we have our call to our auto mapper config method.

public static void Configure()  
{
    Mapper.Initialize(cfg => {
        cfg.AddProfile(new SourceToDestinationProfile());
    });
}

public class SourceToDestinationProfile : Profile  
{
    protected override void Configure()
    {
        Mapper.CreateMap<Source, Destination>();
    }
}

So Automapper was configured correctly and called before the test ran. So what’s the issue?

Automapper.Initialize want to be called only one time, because it resets the config if you call it again. Unit test are supposed to be isolated tests that run independently so that any time the constructor for a test gets called it resets Automapper. The problem happens when you have tests that run asynchronously and reset Automapper.

The Fix.

Lock an object and configure it once.

private static readonly object Sync = new object();  
private static bool _configured;

public static void Configure()  
{
    lock (Sync)
    {
        if (!_configured)                
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile(new SourceToDestinationProfile());
            });
        _configured = true;
    }
}

This did the trick. It lets you run an individual test or the entire test suite. It makes sure that the Mapper is initialized once and then any parallel test wait until it is configured.