How do I get AutoMapper to not cache mapped objects?

前端 未结 5 1758
不思量自难忘°
不思量自难忘° 2021-02-04 00:37

When AutoMapper encounters an object that\'s already been mapped, it seems to use that object again, instead of trying to re-map it. I believe it does this based on .Equal

5条回答
  •  梦如初夏
    2021-02-04 00:56

    When AutoMapper encounters an object that's already been mapped, it seems to use that object again, instead of trying to re-map it. I believe it does this based on .Equals()

    Can you explain why and when you see that ?

    After a quick look in the source code, I'm sure there is no cache for objects. Here is a test that illustrate this :

       public class CustomerSource
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public DateTime DateOfBirth { get; set; }
    
            public int NumberOfOrders { get; set; }
        }
    
        public class CustomerTarget
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public DateTime DateOfBirth { get; set; }
    
            public int NumberOfOrders { get; set; }
        }
    
        [TestMethod]
        public void Test_AutoMapper()
        {
            Mapper.CreateMap();
    
            var source = new CustomerSource() { DateOfBirth = DateTime.Now, FirstName = "FirstName", LastName = "LastName", NumberOfOrders = int.MaxValue };
    
            var res1 = Mapper.Map(source);
            Console.WriteLine(res1.FirstName); // PRINT FirstName
    
            source.FirstName += "[UPDATED]";
            source.LastName += "[UPDATED]";
    
            var res2 = Mapper.Map(source);
            Console.WriteLine(res1.FirstName); // PRINT FirstName[UPDATED]
    
        }
    

    Without your code, it is difficult to go more deeply. There is also a method Mapper.Reset() that clears the MapperEngine and the MapingConfiguration (all internal mapping expressions will be lost)

提交回复
热议问题