Asp.net
Automapper - 映射器已初始化錯誤
我在我的 ASP.NET MVC 5 應用程序中使用 AutoMapper 6.2.0。
當我通過控制器呼叫我的視圖時,它會顯示所有內容。但是,當我刷新該視圖時,Visual Studio 顯示錯誤:
System.InvalidOperationException: ‘映射器已經初始化。您必須為每個應用程序域/程序呼叫一次初始化。
我只在一個控制器中使用 AutoMapper。尚未在任何地方進行任何配置,也未在任何其他服務或控制器中使用 AutoMapper。
我的控制器:
public class StudentsController : Controller { private DataContext db = new DataContext(); // GET: Students public ActionResult Index([Form] QueryOptions queryOptions) { var students = db.Students.Include(s => s.Father); AutoMapper.Mapper.Initialize(cfg => { cfg.CreateMap<Student, StudentViewModel>(); }); return View(new ResulList<StudentViewModel> { QueryOptions = queryOptions, Model = AutoMapper.Mapper.Map<List<Student>,List<StudentViewModel>(students.ToList()) }); } // Other Methods are deleted for ease...控制器內的錯誤:
我的模型類:
public class Student { [Key] public int Id { get; set; } public string Name { get; set; } public string CNIC { get; set; } public string FormNo { get; set; } public string PreviousEducaton { get; set; } public string DOB { get; set; } public int AdmissionYear { get; set; } public virtual Father Father { get; set; } public virtual Sarparast Sarparast { get; set; } public virtual Zamin Zamin { get; set; } public virtual ICollection<MulaqatiMehram> MulaqatiMehram { get; set; } public virtual ICollection<Result> Results { get; set; } }我的視圖模型類:
public class StudentViewModel { [Key] public int Id { get; set; } public string Name { get; set; } public string CNIC { get; set; } public string FormNo { get; set; } public string PreviousEducaton { get; set; } public string DOB { get; set; } public int AdmissionYear { get; set; } public virtual FatherViewModel Father { get; set; } public virtual SarparastViewModel Sarparast { get; set; } public virtual ZaminViewModel Zamin { get; set; } }
當您刷新視圖時,您正在創建一個新的實例
StudentsController- 並因此重新初始化您的 Mapper - 導致錯誤消息“Mapper 已初始化”。從入門指南
我在哪裡配置 AutoMapper?
如果您使用的是靜態 Mapper 方法,則每個 AppDomain 只應進行一次配置。這意味著放置配置程式碼的最佳位置是在應用程序啟動中,例如用於 ASP.NET 應用程序的 Global.asax 文件。
設置它的一種方法是將所有映射配置放入靜態方法中。
App_Start/AutoMapperConfig.cs:
public class AutoMapperConfig { public static void Initialize() { Mapper.Initialize(cfg => { cfg.CreateMap<Student, StudentViewModel>(); ... }); } }然後在Global.asax.cs中呼叫這個方法
protected void Application_Start() { App_Start.AutoMapperConfig.Initialize(); }現在您可以(重新)在控制器操作中使用它。
public class StudentsController : Controller { public ActionResult Index(int id) { var query = db.Students.Where(...); var students = AutoMapper.Mapper.Map<List<StudentViewModel>(query.ToList()); return View(students); } }
如果您想/需要在單元測試場景中堅持使用靜態實現,請注意您可以
AutoMapper.Mapper.Reset()在呼叫初始化之前呼叫。請注意,如文件中所述,這不應在生產程式碼中使用。資料來源:AutoMapper 文件。
