簡體   English   中英

Automapper 全局目標實例化器

[英]Automapper global destination instantiator

我正在使用 automapper 將我的 DTO 映射到 Viewmodels,我的一些 viewmodels 依賴於服務。

我找到了幾種使用這些依賴項構造目標對象的方法,但我想知道是否可以只使用全局對象解析器(在我的情況下是 UnityContainer)?

我目前的解決方案是這樣的:

config.CreateMap<SurveyDTO, SurveyViewModel>()
                .ConstructUsing(x => _ObjectResovler.Resolve<SurveyViewModel>())

或者

config.CreateMap<SurveyDTO, SurveyViewModel>()
                .ConstructUsingServiceLocator()

但這意味着我必須在每個映射中包含這樣的一行。 有沒有辦法只將解析器用於所有映射而不在配置中指定它?

我通過使用解決了它

config.ForAllMaps((map, opts) => opts
          .ConstructUsing(x => _ObjectResovler.Resolve(map.DestinationType)));

對於 servicelocator 替代方案,您可以使用:

config.ForAllMaps((map, opts) => opts.ConstructUsingServiceLocator());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM