只是为了补充吉米的答案,这里是在没有静态映射器的情况下使用 AutoMapper 所需的代码
自版本 4.2.1 起Automapper 有一个经过认可的非静态映射器和配置(感谢 Jimmy!)。
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<ClassA, ClassB>();
});
var mapper = config.CreateMapper();
新版本中还有许多其他有用的选项(例如配置文件)用于创建不同的映射器实例。
您可以在官方文档
(适用于版本 4.1.1)
// Configuration
AutoMapper.Mappers.MapperRegistry.Reset();
var autoMapperCfg = new AutoMapper.ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers);
var mappingEngine = new AutoMapper.MappingEngine(autoMapperCfg);
autoMapperCfg.Seal();
//Usage example
autoMapperCfg.CreateMap<ClassA, ClassB>();
var b = mappingEngine.Map<ClassB>(a);
(适用于版本 3.2.1)
// Configuration
var platformSpecificRegistry = AutoMapper.Internal.PlatformAdapter.Resolve<IPlatformSpecificMapperRegistry>();
platformSpecificRegistry.Initialize();
var autoMapperCfg = new AutoMapper.ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers);
var mappingEngine = new AutoMapper.MappingEngine(autoMapperCfg);
//Usage example
autoMapperCfg.CreateMap<ClassA, ClassB>();
var b = mappingEngine.Map<ClassB>(a);
(适用于版本 2.2.1)
// Configuration
var autoMapperCfg = new AutoMapper.ConfigurationStore(new AutoMapper.TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.AllMappers());
var mappingEngine = new AutoMapper.MappingEngine(autoMapperCfg);
//Usage example
autoMapperCfg.CreateMap<ClassA, ClassB>();
var b = mappingEngine.Map<ClassB>(a);