Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

automapper

I have a couple of ASP.Net apps that share mapping code, so I've created a generic automapper init class.

However, in one of my apps, I have some specific classes that I want added to the configuration.

I have the following code:

public class AutoMapperMappings
{
    public static void Init()
    {
        AutoMapper.Mapper.Initialize(cfg =>
        {
            ... A whole bunch of mappings here ...
        }
    }
}

and

// Call into the global mapping class
AutoMapperMappings.Init();

// This erases everything
AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<CustomerModel, CustomerInfoModel>());

How do I add this unique mapping without destroying what is already initialized?

like image 761
Scottie Avatar asked Aug 21 '16 23:08

Scottie


People also ask

How do I configure Mapper?

Create a MapperConfiguration instance and initialize configuration via the constructor: var config = new MapperConfiguration(cfg => { cfg. CreateMap<Foo, Bar>(); cfg. AddProfile<FooProfile>(); });


1 Answers

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.

like image 135
Toine Seiter Avatar answered Sep 20 '22 13:09

Toine Seiter