AutoMapper如何合并通用Profile与项目专属映射规则?
AutoMapper合并通用与项目专属映射规则的解决方案
AutoMapper完全支持合并通用与项目专属的映射规则,核心是避免重复创建相同的映射类型对,而是在已有通用规则的基础上叠加专属配置,以下是具体实现方式:
1. 基于已有映射添加专属规则
在通用Profile中先定义基础映射逻辑,项目专属Profile中不要重新调用CreateMap<B, BModel>(),而是通过FindTypeMapFor方法找到已存在的映射配置,再追加专属规则:
// Common项目的CommonAutoMapperProfile public class CommonAutoMapperProfile : Profile { public CommonAutoMapperProfile() { // 定义通用基础映射规则 CreateMap<B, BModel>() .ForMember(dest => dest.Prop1, opt => opt.MapFrom(src => src.Prop1)) .ForMember(dest => dest.Prop2, opt => opt.MapFrom(src => src.Prop2)); } } // 项目1专属Profile:添加Prop3的映射规则 public class Project1Profile : Profile { public Project1Profile() { var existingMap = FindTypeMapFor<B, BModel>(); existingMap.ForMember(dest => dest.Prop3, opt => opt.MapFrom(src => src.Prop3)); } } // 项目2专属Profile:忽略Prop3 public class Project2Profile : Profile { public Project2Profile() { var existingMap = FindTypeMapFor<B, BModel>(); existingMap.ForMember(dest => dest.Prop3, opt => opt.Ignore()); } }
2. 严格控制Profile加载顺序
初始化AutoMapper时,必须先加载通用Profile,再加载项目专属Profile,这样专属规则会叠加到通用规则之上,而非覆盖:
// 项目1的初始化代码 var config = new MapperConfiguration(cfg => { cfg.AddProfile<CommonAutoMapperProfile>(); cfg.AddProfile<Project1Profile>(); }); var mapper = config.CreateMapper(); // 项目2的初始化代码 var config = new MapperConfiguration(cfg => { cfg.AddProfile<CommonAutoMapperProfile>(); cfg.AddProfile<Project2Profile>(); }); var mapper = config.CreateMapper();
3. 利用继承关系(IncludeBase)实现规则复用
如果视图模型存在继承关系,可以将通用规则定义在基础模型的映射中,项目专属映射通过IncludeBase继承通用规则,再添加专属配置:
// Common项目:定义基础模型与通用映射 public class BBaseModel { public string Prop1 { get; set; } public string Prop2 { get; set; } } public class CommonAutoMapperProfile : Profile { public CommonAutoMapperProfile() { CreateMap<B, BBaseModel>(); } } // 项目1:BModel继承BBaseModel,继承通用规则并添加Prop3映射 public class BModel : BBaseModel { public string Prop3 { get; set; } } public class Project1Profile : Profile { public Project1Profile() { CreateMap<B, BModel>() .IncludeBase<B, BBaseModel>() .ForMember(dest => dest.Prop3, opt => opt.MapFrom(src => src.Prop3)); } }
内容的提问来源于stack exchange,提问作者C Howell
相关产品推荐
相关产品推荐

