日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

[AutoMapper]反射自动注册AutoMapper Profile

發布時間:2023/11/27 生活经验 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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容器中了

轉載于:https://www.cnblogs.com/wwwblender-3dcn/p/10165258.html

總結

以上是生活随笔為你收集整理的[AutoMapper]反射自动注册AutoMapper Profile的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。