How to register a custom ObjectMapper with AutoMap

2019-05-23 14:46发布

I am planning to create my own custom Object Mapper for a type using AutoMapper's IObjectMapper interface, but I don't see any place where we can register the implemented mapper with AutoMapper. Could anyone tell me how to register it.

Edit: For more information on this please follow the discussion at AutoMapper-Users group

标签: c# AutoMapper
1条回答
欢心
2楼-- · 2019-05-23 15:14

One way to go here is to replace the static registry function in the MapperRegistry class. Here's the current version:

public static Func<IEnumerable<IObjectMapper>> AllMappers = () => new IObjectMapper[]
{
#if !SILVERLIGHT
    new DataReaderMapper(),
#endif
    new TypeMapMapper(TypeMapObjectMapperRegistry.AllMappers()),
    new StringMapper(),
    new FlagsEnumMapper(),
    new EnumMapper(),
    new ArrayMapper(),
    new EnumerableToDictionaryMapper(),
    new DictionaryMapper(),
#if !SILVERLIGHT
    new ListSourceMapper(),
#endif
    new EnumerableMapper(),
    new AssignableMapper(),
    new TypeConverterMapper(),
    new NullableMapper()
};

You'd basically copy that one, and do something like:

MapperRegistry.AllMappers = () => new IObjectMapper[] {
   // Insert your custom mapper somewhere in this list
};

Just do that before you do any Mapper.CreateMap or Mapper.Initialize business. Mappers are evaluated in order.

查看更多
登录 后发表回答