AutoMapper mapping fails randomly when defining mappings locally

时间:2015-05-12 23:42:33

标签: asp.net-web-api automapper

We are configuring automapper for my asp.net MVC/Web API project in the method definition as follows.

print("Please enter a word to be guessedthat does not contain ? or white space: ",end='')
while True:
  try:
      secret_word=input()
  except '?' or 'print()'
      print("Please enter a word to be guessedthat does not contain ? or white space: ",end='')
      continue
  else:
      break

We are noticing that api is randomly not mapping values and response json is returning null values for the mapped fields.

When this happens I'm recycling the app pool and it seems to work for a period of time and we run into the issue again.

Documentation refers to storing all the mappings in Application_Start in Global.asax. However, we are setting them in the method definition - Is that why we are seeing this issue?

1 个答案:

答案 0 :(得分:1)

问题是Web应用程序是线程化的,而Automapper并不是完全线程安全的。即有一些方法和类是线程安全的,而另一些则不是。如果你使用静态类Mapper,可能会发生这样的情况:当一个线程试图映射对象时,另一个线程试图重新定义映射,这就是你得到这些随机错误的原因。

正如Jasen在他的评论中所说,并且你自己在你的问题中说,一个解决方案是在中心位置定义所有映射,只有一次,并且在执行第一个请求之前,通常在Application_Start

另一种选择是使用AutoMapper中的非静态类。即而不是使用Mapper使用其他非静态类。通过这种方式,每个线程都有自己的实例,并且线程安全性不是一致的。有关该问题的更多信息以及此替代解决方案,请参阅此问答:Is Mapper.Map in AutoMapper thread-safe?

顺便说一句,从性能的角度来看,定义映射只需一次并重用它们要好得多,而不是一直重新定义它们。最有可能AutoMapper使用Reflection,如果是这样,那么缓存类型和属性信息是非常可取的,不会降低性能。