0

我有一个使用带有静态映射的 Automapper 7.0.1 的 ASP.Net Web API。我最近升级到没有静态映射的 Automapper 9.0.0。因此,我使用了推荐的方式,即使用我的依赖容器(Unity Container)将实例注册IMapperIConfigurationProviderSingletons。

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 一起使用。升级后我错过了什么?

4

1 回答 1

-1

原来有2个问题。

  1. 我需要使用Profile包含所有映射的 a。所以我将所有映射从 a 移动MapperConfiguration到 aProfile如下

    public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile()
        {
            CreateMap<DtoReq, Model>();
            // other mappings
        }
    }
    

    然后,使用MapperConfigurationExpression如下

    var mce = new MapperConfigurationExpression();
    mce.ConstructServicesUsing(o => MyUnityContainer);
    mce.AddProfiles(new List<Profile>() { new AutoMapperProfile() });
    var mc = new MapperConfiguration(mce);
    mc.CompileMappings(); // prevents lazy compilation
    mc.AssertConfigurationIsValid(); // ensures all mappings are in place
    
  2. 缺少一些在旧版本中有效的映射(只有 2 个)可能是因为默认情况下启用了自动映射。新版本 9.0.0 仅在我将它们移动到Profile.

于 2020-03-09T11:17:49.170 回答