Automapper - why use Mapper.Initialize?

2020-06-08 17:14发布

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.

标签: c# AutoMapper
2条回答
我想做一个坏孩纸
2楼-- · 2020-06-08 17:26

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.

查看更多
何必那么认真
3楼-- · 2020-06-08 17:45

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));
    }
}
查看更多
登录 后发表回答