我通常不会在这里问这样的问题,但不幸的是,虽然AutoMapper似乎是一个很好的映射库,但它的文档非常糟糕 - 没有关于库方法的XML文档,以及我能找到的最官方的在线文档是这样,非常活跃.如果有人有更好的文档,请告诉我.
那就是说,这就是问题:为什么要使用Mapper.Initialize?它似乎没有必要,因为你可以Mapper.CreateMap立即使用,因为没有文档我不知道Initialize该做什么.
我在AutoMapper用户列表中询问过,这个答案基本上说明了原因:
https://groups.google.com/forum/?fromgroups=#!topic/automapper-users/0RgIjrKi28U
这与允许AutoMapper进行确定性(随机)优化有关.在性能方面,最好在Initialize呼叫中创建所有映射.
初始化运行所有地图创建一次,然后在您进行映射时完成.您可以随时创建地图,但这会降低代码速度,因为映射创建涉及反射.
我发现最好使用配置文件作为我的映射代码,并使用以下内容来完成所有设置:
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));
}
}
Run Code Online (Sandbox Code Playgroud)