Asp.net-Mvc-3
AutoMapper 執行緒問題(缺少類型映射配置或不支持的映射)?
我不確定我這裡是否有執行緒問題。在頁面載入時,我正在執行兩個 Ajax 請求以從第三方 API 載入一些附加數據。以下是每個方法被呼叫的樣子:
private List<CaseCommentModel> GetCaseCommentModels(string caseId) { var comments = CaseService.GetAllCaseCommentsByCaseId(caseId); Mapper.Reset(); Mapper.CreateMap<CrmCaseComment, CaseCommentModel>(); var caseCommentModels = Mapper.Map<List<CrmCaseComment>, List<CaseCommentModel>>(comments); return caseCommentModels; } private List<CaseAttachmentModel> GetCaseAttachmentModels(string caseId) { var attachments = AttachmentService.GetAttachmentsByParentId(caseId); Mapper.Reset(); Mapper.CreateMap<CrmAttachment, CaseAttachmentModel>(); var caseAttachmentModels = Mapper.Map<List<CrmAttachment>, List<CaseAttachmentModel>>(attachments); return caseAttachmentModels; }有時兩種反應都會成功。但是,如果我刷新頁面,有時會失敗,並出現以下異常:
Missing type map configuration or unsupported mapping我可以在不進行任何程式碼更改的情況下從兩個請求成功到一個失敗;只需刷新頁面即可。這是執行緒問題還是我錯誤地使用了映射器?
您應該在每個應用程序生命週期內只創建一次映射。因此,將每個特定移動
CreateMap到應用程序啟動。您遇到的問題可能與在其他執行緒呼叫之前進行映射的競爭有關
Mapper.Reset()
是的,您遇到了執行緒問題,並且您濫用了 Automapper 配置。從 Automapper入門頁面:
如果您使用的是靜態 Mapper 方法,則每個 AppDomain 只需進行一次配置。這意味著放置配置程式碼的最佳位置是在應用程序啟動中,例如用於 ASP.NET 應用程序的 Global.asax 文件。通常,配置引導程序類在其自己的類中,並且從啟動方法呼叫此引導程序類。
因此,您不應該
Mapper.CreateMap在控制器內部將它們移動到公共位置並執行一次。或者,如果您確實需要動態映射配置,請不要使用靜態
Mapper而不是“手動”建構配置和引擎:var config = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers()); config.CreateMap<CrmCaseComment, CaseCommentModel>(); var engine = new MappingEngine(config); var caseCommentModels = engine.Map<List<CrmCaseComment>, List<CaseCommentModel>>(comments);