我在ASP.NET MVC 5应用程序中使用了AutoMapper 6.2.0。
当我通过 Controller 调用 View 时,它显示一切正常。但是,当我刷新该 View 时,Visual Studio显示错误:
System.InvalidOperationException: 'Mapper already initialized. You must call Initialize once per application domain/process.'
我仅在一个 Controller 中使用AutoMapper。尚未在任何地方进行任何配置,也未在任何其他服务或 Controller 中使用AutoMapper。
我的 Controller :
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...
Controller 内错误:
我的模特类:
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; }
}
我的ViewModel类:
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; }
}
最佳答案
刷新 View 时,您正在创建StudentsController
的新实例-并因此重新初始化了Mapper-导致出现错误消息“Mapper已初始化”。
从Getting Started Guide
Where do I configure AutoMapper?
If you're using the static Mapper method, configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications.
一种设置方法是将所有映射配置放入静态方法中。
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();
}
现在,您可以在 Controller 操作中(重新)使用它。
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);
}
}
关于asp.net - 自动映射器-映射器已初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241708/