我通常不会在这里问这样的问题,但不幸的是,虽然AutoMapper似乎是一个很好的映射库,但它的文档非常糟糕-没有关于该库方法的XML文档,而且我能找到的最官方的在线文档是this,它非常活跃。如果有人有更好的文档,请让我知道。
也就是说,这里有一个问题:为什么要使用Mapper.Initialize
?它似乎不是必需的,因为你可以立即使用Mapper.CreateMap
,而且由于没有文档,我不知道Initialize
是做什么的。
发布于 2012-10-22 22:23:19
我在AutoMapper用户列表上询问,这个答案基本上说明了原因:
https://groups.google.com/forum/?fromgroups=#!topic/automapper-users/0RgIjrKi28U
这与允许AutoMapper进行确定性(随机)优化有关。在性能方面,最好在Initialize
调用中创建所有映射。
发布于 2012-10-19 23:34:20
初始化只运行一次所有的映射创建,因此当您进行映射时,它就完成了。您可以随时创建一个map,但这会减慢您的代码,因为映射创建涉及到反射。
我发现最好对我的映射代码使用配置文件,并使用类似下面的代码来完成所有设置:
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));
}
}
https://stackoverflow.com/questions/12977273
复制相似问题