AutoMapper IIS回收引发的 未将对象引用设置到对象实例

一、前言

最近使用AutoMapper的时候,一段时间久会产生System.NullReferenceException:未将对象引用设置到对象的实例。这个问题。后来通过测试,发现部署在IIS上的站点,默认情况下,IIS会在每个间隔固定时间回收AppPool,如果刚刚好有很多请求访问调用了AutoMapper映射的接口,就会产生如下问题。

System.NullReferenceException: 未将对象引用设置到对象的实例。
   在 AutoMapper.TypeMapFactory.<>c__DisplayClass3_0.<MapDestinationPropertyToSource>b__0(IMemberConfiguration _)
   在 System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
   在 AutoMapper.TypeMapFactory.CreateTypeMap(Type sourceType, Type destinationType, IProfileConfiguration options, MemberList memberList)
   在 AutoMapper.ConfigurationStore.<>c__DisplayClass80_0.<CreateTypeMap>b__0(TypePair tp)
   在 System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   在 AutoMapper.ConfigurationStore.CreateMap[TSource,TDestination](String profileName, MemberList memberList)
   在 PaymentPlatform.Test.AutoMapperTest.ProcessRequest(HttpContext context)

二、解决方案

方法一

打开对应IIS站点的应用程序池,点击高级设置。如下图:

将上图中的固定时间间隔(分钟)设置为0.

方法二

可在全局的Application_Start中,定义所有的AutoMapper类型映射。这样就可以保证映射关系的一次性初始化。后续代码无需再定义,只需关注对象转换就可以了。

方法三

也可使用AutoMapper扩展这种方式进行使用,对于不存在的配置,自动创建相关的映射。

posted @ 2017-11-13 00:23  简玄冰  阅读(1419)  评论(3编辑  收藏  举报