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?
Create a MapperConfiguration instance and initialize configuration via the constructor: var config = new MapperConfiguration(cfg => { cfg. CreateMap<Foo, Bar>(); cfg. AddProfile<FooProfile>(); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With