2017年6月19日 星期一

【AutoMapper】None static centralized configuration

想把 AutoMapper 的設定作個集中,但找到的教學都是用 Initialize 做靜態的,而沒有新版建議的 IMapper 實體導向的作法,參考了 SO 得其中一篇作了簡單的設置,算不上 best practice 但有興趣的人還是可以參考下。

Configuration class
  1. public class AutoMapperWebConfiguration
  2. {
  3. public static MapperConfiguration Configure()
  4. {
  5. return new MapperConfiguration(cfg =>
  6. {
  7. cfg.AddProfile(new MeetingProfile());
  8. cfg.AddProfile(new ClubProfile());
  9. });
  10. }
  11. }

Profile 範例
  1. public class ClubProfile : Profile
  2. {
  3. public ClubProfile()
  4. {
  5. CreateMap<ClubViewModel, Club>();
  6. CreateMap<Club, ClubViewModel>()
  7. .ForMember(dest => dest.DisplayText, opt => opt.ResolveUsing(src =>
  8. {
  9. if (string.IsNullOrEmpty(src.ChineseAbbr))
  10. {
  11. return $"{src.Name}({src.Abbr})";
  12. }
  13. else
  14. {
  15. return $"{src.ChineseAbbr}({,src.Abbr})";
  16. }
  17. }));
  18. }
  19. }
相對於使用前直接建 config,套用 Profile 的話,官方建議在其初始化時做 CreateMap()。
以上兩個我是開一個 AutoMapper 資料夾裝一起,不太確定最佳實作應該是怎麼做。

然後在 Global.asax 讓程式跑起來的時候把設定一併帶起來。
  1. public class MvcApplication : System.Web.HttpApplication
  2. {
  3. internal static MapperConfiguration MapperConfig { get; set; }
  4.  
  5. protected void Application_Start()
  6. {
  7. // skip
  8.  
  9. MapperConfig = AutoMapperWebConfiguration.Configure();
  10. }
  11. }

在 Controller 就有 mapper 可以建來用了
  1. public class MeetingsController : Controller
  2. {
  3. private IMapper _mapper = MvcApplication.MapperConfig.CreateMapper();
  4.  
  5. // GET: Meetings
  6. public ActionResult Index()
  7. {
  8. // skip
  9. }
  10. }

ref:SO

沒有留言:

張貼留言