blender模型下载

blender模型下载https://www.blender-3d.cn/ Blender3D模型库

[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容器中了

posted on 2018-12-23 19:22  www.blender-3d.cn  阅读(587)  评论(1编辑  收藏  举报

导航