Reputation: 30063
I wouldn't normally ask this kind of question on here, but unfortunately whilst AutoMapper seems to be a good mapping library, its documentation is woefully bad - there is no XML documentation for the library's methods, and the most official online documentation I could find was this, which is very brisk. If anyone has any better documentation, please let me know.
That said, here's the question: why use Mapper.Initialize
? It doesn't seem to be required as you can just use Mapper.CreateMap
immediately, and as there is no documentation I have no clue what Initialize
is meant to do.
Upvotes: 17
Views: 21460
Reputation: 30063
I asked on the AutoMapper users list, and this answer basically says why:
https://groups.google.com/forum/?fromgroups=#!topic/automapper-users/0RgIjrKi28U
It's something to do with allowing AutoMapper to do deterministic (stochastic) optimization. Performance-wise, it's better to get all your mappings created in the Initialize
call.
Upvotes: 9
Reputation: 5241
The initialization runs all the map creation once so it is then done when you come to do your mapping. You can create a map whenever you want, but this will slow your code down as the mapping creation involves reflection.
I find it best to use profiles for my mapping code and use something like the following to get this all setup:
public class AutoMapperConfiguration : IRequiresConfigurationOnStartUp
{
private readonly IContainer _container;
public AutoMapperConfiguration(IContainer container)
{
_container = container;
}
public void Configure()
{
Mapper.Initialize(x => GetAutoMapperConfiguration(Mapper.Configuration));
}
private void GetAutoMapperConfiguration(IConfiguration configuration)
{
var profiles = GetProfiles();
foreach (var profile in profiles)
{
configuration.AddProfile(_container.GetInstance(profile) as Profile);
}
}
private static IEnumerable<Type> GetProfiles()
{
return typeof(AutoMapperConfiguration).Assembly.GetTypes()
.Where(type => !type.IsAbstract && typeof(Profile).IsAssignableFrom(type));
}
}
Upvotes: 7