1. 程式人生 > >封裝一個Automapper單例

封裝一個Automapper單例

  public class DataModule : IModule
    {
        public void Configure(IMapperConfigurationExpression cfg)
        {
            //cfg.CreateMap<ApproveAtcPo, ApproveAtcVo>().ReverseMap();
       
        }
    }
         /// <summary>
        /// 註冊需要轉換的型別
        /// </summary>
        private
PoMapper() { AutoMapper.Mapper.Initialize(cfg => {
//多模組註冊方式
new DataModule().Configure(cfg); new AliasModule().Configure(cfg); }); }

 

 1     public class MapperTool
 2     {
 3
private static volatile MapperTool mapper = null; 4 private static object syncRoot = new Object(); 5 public static readonly List<Type> typeList = null; 6 /// <summary> 7 /// 註冊需要轉換的型別 8 /// </summary> 9 private MapperTool() 10 {
11 Mapper.Initialize(cfg => 12 { 13 //指定不同屬性對映demo 14 //cfg.CreateMap<auth_userVo, t_auth_user>() 15 // .ReverseMap() 16 // .ForMember(dest => dest.id, opt => opt.MapFrom(src => src.rid)) 17 // .ForMember(dest => dest.update, opt => opt.MapFrom(src => src.create)); 18 19 }); 20 //驗證是否所有欄位都轉換了 21 //Mapper.Configuration.AssertConfigurationIsValid(); 22 } 23 24 private MapperTool(List<Type[]> TypeList) 25 { 26 Mapper.Initialize(cfg => 27 { 28 foreach (var type in TypeList) 29 { 30 cfg.CreateMap(type[0], type[1]).ReverseMap(); 31 } 32 }); 33 } 34 35 36 /// <summary> 37 /// 初始化註冊Mapper 38 /// </summary> 39 public static MapperTool Instance 40 { 41 get 42 { 43 if (mapper == null) 44 { 45 lock (syncRoot) 46 { 47 if (mapper == null) 48 { 49 mapper = new MapperTool(); 50 } 51 52 } 53 } 54 return mapper; 55 } 56 } 57 58 /// <summary> 59 /// 傳入需要轉換的物件 60 /// </summary> 61 /// <typeparam name="F">需要轉換的物件型別</typeparam> 62 /// <typeparam name="T">轉換目標物件型別</typeparam> 63 /// <param name="f">需要轉換的物件</param> 64 /// <returns>目標物件</returns> 65 public T Map<F, T>(F f) 66 where F : new() 67 where T : new() 68 { 69 return Mapper.Map<F, T>(f); 70 } 71 }
View Code