We use automapper with ASP.NET Core 2.0.
We like to create a mapping configuration once, which will be used from each mapper. We create a mapper per request that we will not have problems because I read once automapper is not thread safe.
We like to precompile the mappingconfiguration at application startup (See in Code MapperConfigruation.CompileMappings();
If I measure the time how long the mapping takes, i see that the first mapping need more time than the other mappings. Is there a reason for that or do I have bug?
Code
In ConfigureService of Startup class:
services.AddSingleton<MyMapperConfiguration>();
services.AddScoped<IObjectMapper, MyMapper>();
Mapperconfiguration
public class MyMapperConfiguration
{
public MapperConfiguration MapperConfiguration { get; private set; }
public MappingDefinition MappingDefinition { get; }
public MapperConfiguration(IOptions<MappingDefinition> mappings)
{
// MappingDefinitions hold some information where to search mappings
MappingDefinition = mappings.Value;
}
public void Configure()
{
List<Type> mappingDefinitionClasses = new List<Type>();
// Search Types with special attribute and add it to the typelist
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfiles(mappingDefinitionClasses.ToArray());
});
MapperConfiguration.CompileMappings(); // <-- THIS SHOULD COMPILE THE MAPPING I THNIK?!
}
`
Mapper
public class MyMapper : IObjectMapper
{
public IMapper Mapper { get; }
public Mapper(MapperConfiguration mappingConfiguration)
{
Mapper = mappingConfiguration.MapperConfiguration.CreateMapper();
}
public TDestination Map<TSource, TDestination>(TSource source)
{
return Mapper.Map<TSource, TDestination>(source);
}
}
IObjectMapper:
public interface IObjectMapper
{
TDestination Map<TSource, TDestination>(TSource source);
}
Measure time inside a webApi
Stopwatch sw = new Stopwatch();
sw.Start();
destObj = _mapper.Map<Source, Destination>(sourceObj);
sw.Stop();
Debug.WriteLine($"Duration of mapping: {sw.ElapsedMilliseconds}");
In the Configruate methode of Startup I also get an instance of the mapping configuration and call Configure() that this instance lifes.