AutoMapper How To Map Object A To Object B Differently Depending On Context

后端 未结 3 999
面向向阳花
面向向阳花 2020-12-24 09:16

Calling all AutoMapper gurus!

I\'d like to be able to map object A to object B differently depending on context at runtime. In particular, I\'d like to ignore certai

3条回答
  •  情歌与酒
    2020-12-24 09:53

    Just to complement Jimmy's answer here's the code needed to use AutoMapper without the static Mapper

    As of version 4.2.1 Automapper has a sanctioned non static mapper and configuration (thanks Jimmy!).

    var config = new MapperConfiguration(cfg => {
        cfg.CreateMap();
    });
    
    var mapper = config.CreateMapper();
    

    There are many other useful options (such as profiles) in the new releases for creating different mapper instances. You can get all the details in the official documentation

    (correct for version 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();
    
    var b = mappingEngine.Map(a);
    

    (correct for version 3.2.1)

    // Configuration
    var platformSpecificRegistry = AutoMapper.Internal.PlatformAdapter.Resolve();
    platformSpecificRegistry.Initialize();
    
    var autoMapperCfg = new AutoMapper.ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers);
    var mappingEngine = new AutoMapper.MappingEngine(autoMapperCfg);
    
    //Usage example
    autoMapperCfg.CreateMap();
    
    var b = mappingEngine.Map(a);
    

    (correct for version 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();
    
    var b = mappingEngine.Map(a);
    

提交回复
热议问题