How can I add a mapping in AutoMapper after Initialize has been called?

A quick sample that allows you to initialize your AutoMapper 5.x several times... Ok it's not very nice ;)

public static class MapperInitializer
{
    /// <summary>
    /// Initialize mapper
    /// </summary>
    public static void Init()
    {
        // Static mapper
        Mapper.Initialize(Configuration);

        // ...Or instance mapper
        var mapperConfiguration = new MapperConfiguration(Configuration);
        var mapper = mapperConfiguration.CreateMapper();
        // ...
    }

    /// <summary>
    /// Mapper configuration
    /// </summary>
    public static MapperConfigurationExpression Configuration { get; } = new MapperConfigurationExpression();
}

// First config 
MapperInitializer.Configuration.CreateMap(...);
MapperInitializer.Init(); // or not

//...
MapperInitializer.Configuration.CreateMap(...);
MapperInitializer.Init();

The idea is to store the MapperConfigurationExpression instead of the MapperConfiguration instance.


You can't, but rather than initialize the Mappings from your Init method, you could get it to return a function that can be called inside a Mapper.Initialize() call.

So, your Init method looks like this:

public static Action<IMapperConfigurationExpression> Init()
{
    return (cfg) => {
        ... A whole bunch of mappings here ...
    };
}

Then from your app where you want extra mappings:

var mappingsFunc = MyClass.Init();

Mapper.Initialize((cfg) => {
    mappingsFunc(cfg);
    ... Extra mappings here ...
});

or you could reduce it a little...

Mapper.Initialize((cfg) => {
    MyClass.Init()(cfg);
    ... Extra mappings here ...
});

Hope this helps.


This should be possible if you use the instance API that AutoMapper provides instead of the static API. This wiki page details the differences between the two.

Essentially instead of calling AutoMapper.Mapper.Initialize(cfg => ...) again for your additional mapping, which overwrites the entire global mapper configuration with that single mapping, you'll need to create another mapper object with the instance API using:

var config = new MapperConfiguration(cfg =>
    cfg.CreateMap<CustomerModel, CustomerInfoModel>()
);
var mapper = config.CreateMapper();

Of course in order to use this new mapper you will have to do something like var mappedModel = mapper.Map<CustomerInfoModel>(new CustomerModel()); specifically when mapping objects using your additional mapping configuration. Whether that's practical in your case, I don't know, but I believe this is the only way to do what you require.

Tags:

C#

Automapper