zoukankan      html  css  js  c++  java
  • [AutoMapper]反射自动注册AutoMapper Profile

    AutoMapper 帮我我们方便管理物件跟物件之间属性值格式转换

    模型转换

    这里有两个类别

    UserInfoModel 当作我们从DB捞取出来模型资料

    public class UserInfoModel
    {
    	public int RowId { get; set; }
    	public string Name { get; set; }
    	public int Age { get; set; }
    }
    

      

    UserInfoViewModel 是呈现在UI或其他地方的模型  

    其中  Detail栏位由  UserInfoModel NameAge属性组成的

    public class UserInfoViewModel
    {
    	public string Detail { get; set; }
    }
    

      这时我们就会引用AutoMapper 帮我们统一管理转换模型上的问题

    建立一个Profile

    设置UserInfoModel对于UserInfoViewModel之前的栏位转换

    public class UserInfoProfile : Profile
    {
            public UserInfoProfile()
            {
                CreateMap<UserInfoModel, UserInfoViewModel>()
                        .ForMember(t => t.Detail, 
                                        s => s.MapFrom(_ => $"DetailInfo:{_.Name} {_.Age}"));
            }
    }
    

      而我们在注册时会呼叫AddProfile方法

    Mapper.Initialize(x => x.AddProfile<UserInfoProfile>());
    

      但每次新加Profile这边都需要设置新的Profile,我们就会想有没有方法可以让他自动注册?

    我们可以使用反射来完成

    反射自动注册AutoMapper Profile 

    此程式我使用我的 ExtenionTool 

    var profiles =  Assembly.GetExecutingAssembly()
    	.GetInstancesByAssembly<Profile>();
    
    foreach (var profile in profiles)
    {
    	Mapper.Initialize(x => x.AddProfile(profile));
    }
    

      上面程式码很简单清晰,呼叫  取得目前组件所有的  物件实体并且加到中,我们将上面程式码在初始化执行一次GetInstancesByAssembly()ProfileProfile

    public static IEnumerable<TResult> GetInstancesByAssembly<TResult>(this Assembly ass)
    {
    	return ass.GetTypes()
    			.Where(x => typeof(TResult).IsAssignableFrom(x) && x.IsNormalClass())
    			.Select(x => Activator.CreateInstance(x))
    			.Cast<TResult>();
    }
    

      

    核心程式使用Linq 动态取得你所需的类型并使用反射创建

    之后我们就可以不用在手动把Profile加至AutoMapper容器中了

  • 相关阅读:
    jupyter中使用熟悉的vim
    解决安装manjaro中安装ccs10.2的库缺失问题
    Markdown中公式
    诗就应该边读边品的,不要
    为neovim田间python3支持
    bilibili视频保存目录
    新工科教育--之我所见
    父母的爱 和汽车的后背箱
    解决manjaro中jupyter无法修改目录和默认浏览器的问题:
    解决jupyter的能打开python文件无法新建的问题
  • 原文地址:https://www.cnblogs.com/wwwblender-3dcn/p/10165258.html
Copyright © 2011-2022 走看看