Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - Mapper already initialized error

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

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: 'Mapper already initialized. You must call Initialize once per application domain/process.'

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.

My 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... 

Error within controller:

enter image description here

My Model class:

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

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; } } 
like image 572
Rahmat Ali Avatar asked Nov 11 '17 19:11

Rahmat Ali


People also ask

Why do we need AutoMapper?

AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.

Where is AutoMapper configuration?

Where do I configure AutoMapper? ¶ 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.

What is an AutoMapper profile?

automapper Profiles Basic Profile Profiles permit the programmer to organize maps into classes, enhancing code readability and maintainability. Any number of profiles can be created, and added to one or more configurations as needed. Profiles can be used with both the static and instance-based APIs.

What is AutoMapper ASP NET core?

What is AutoMapper? AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.


2 Answers

If you want/need to stick with the static implementation in a unit testing scenario, note that you can call AutoMapper.Mapper.Reset() before calling initialize. Do note that this should not be used in production code as noted in the documentation.

Source: AutoMapper documentation.

like image 164
dasch88 Avatar answered Oct 04 '22 10:10

dasch88


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".

From the 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.

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

Then call this method in the 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);     } } 
like image 28
Jasen Avatar answered Oct 04 '22 12:10

Jasen