我有一个使用带有静态映射的 Automapper 7.0.1 的 ASP.Net Web API。我最近升级到没有静态映射的 Automapper 9.0.0。因此,我使用了推荐的方式,即使用我的依赖容器(Unity Container)将实例注册IMapper为IConfigurationProviderSingletons。
var config = AutoMapperConfig.GetMapperConfiguration();
_container.RegisterInstance<IConfigurationProvider>(config, new SingletonLifetimeManager());
_container.RegisterInstance<IMapper>(new Mapper(config), new SingletonLifetimeManager());
这AutoMapperConfig.GetMapperConfiguration()是一个静态方法,它返回一个包含所有映射的新配置。
public static MapperConfiguration GetMapperConfiguration()
{
return new MapperConfiguration(config =>
{
config.CreateMap<MyDtoReq, MyModel1>(MemberList.Destination);
config.CreateMap<MyModel1, MyDtoRes>(MemberList.Destination);
// other mappings
}
}
Therafter,我已经解决并使用IMapper了许多注册的服务PerRequestLifetimeManager,例如:
_container.RegisterType<IService1, Service1>(new PerRequestLifetimeManager());
我可以看到 Unity 正确解析了 Services 和 Mapper,但是当我调用时Map()使用:
_service1.Mapper.Map<MyDtoRes>(myModel1ObjectInstance);
它给了我一个 AutoMapperException 说
缺少类型映射配置或不支持的映射错误
我尝试了很多事情,包括将 AutoMapper 对象注册为 PerRequest 依赖项,即使是使用静态类(没有 DI 容器)的单例,但无济于事。
我确信我的映射是正确的,因为它们在 v 7.0.1 中与静态 AutoMapper 一起使用。升级后我错过了什么?