自动映射器-映射器已初始化错误 [英] Automapper - Mapper already initialized error

查看:274
本文介绍了自动映射器-映射器已初始化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ASP.NET MVC 5应用程序中使用AutoMapper 6.2.0.

I am using AutoMapper 6.2.0 in my ASP.NET MVC 5 application.

当我通过控制器调用视图时,它显示了所有正确的信息.但是,当我刷新该视图时,Visual Studio显示错误:

When I call my view through controller it shows all things right. But, when I refresh that view, Visual Studio shows an error:

System.InvalidOperationException:'映射器已经初始化.您必须为每个应用程序域/进程调用一次Initialize."

System.InvalidOperationException: 'Mapper already initialized. You must call Initialize once per application domain/process.'

我仅在一个控制器中使用AutoMapper.尚未在任何地方进行任何配置,也未在任何其他服务或控制器中使用AutoMapper.

I am using AutoMapper only in one controller. Not made any configuration in any place yet nor used AutoMapper in any other service or 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...

控制器内错误:

我的模型班:

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类:

My ViewModel Class:

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-导致错误消息已映射器初始化".

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

这篇关于自动映射器-映射器已初始化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆