且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动映射器-映射器已初始化错误

更新时间:2022-02-24 23:07:39

刷新视图时,您正在创建StudentsController的新实例-并因此重新初始化Mapper-导致错误消息已映射器初始化".

When you refresh the view you are creating a new instance of the StudentsController -- and therefore reinitializing your Mapper -- resulting in the error message "Mapper already initialized".

入门指南

我在哪里配置AutoMapper?

如果您使用的是静态Mapper方法,则每个AppDomain只能进行一次配置.这意味着放置配置代码的***位置是在应用程序启动中,例如ASP.NET应用程序的Global.asax文件.

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.

一种设置方法是将所有映射配置放入静态方法中.

One way to set this up is to place all of your mapping configurations into a static method.

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();
}

现在,您可以在控制器操作中(重新)使用它.

Now you can (re)use it in your controller actions.

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);
    }
}